create server package

This commit is contained in:
Evan Almloff committed 2023-03-28 13:35:17 -05:00
1 parent c5085496db
commit 7f6f6fb8c8
8 files changed
+258

No files matched your search

@@ -0,0 +1,23 @@
use crate::{LiveViewError, LiveViewSocket};
use axum::extract::ws::{Message, WebSocket};
use futures_util::{SinkExt, StreamExt};
/// Convert a warp websocket into a LiveViewSocket
///
/// This is required to launch a LiveView app using the warp web framework
pub fn axum_socket(ws: WebSocket) -> impl LiveViewSocket {
ws.map(transform_rx)
.with(transform_tx)
.sink_map_err(|_| LiveViewError::SendingFailed)
}
fn transform_rx(message: Result<Message, axum::Error>) -> Result<String, LiveViewError> {
message
.map_err(|_| LiveViewError::SendingFailed)?
.into_text()
.map_err(|_| LiveViewError::SendingFailed)
}
async fn transform_tx(message: String) -> Result<Message, axum::Error> {
Ok(Message::Text(message))
}
@@ -0,0 +1,25 @@
use futures_util::{SinkExt, StreamExt};
use salvo::ws::{Message, WebSocket};
use crate::{LiveViewError, LiveViewSocket};
/// Convert a salvo websocket into a LiveViewSocket
///
/// This is required to launch a LiveView app using the warp web framework
pub fn salvo_socket(ws: WebSocket) -> impl LiveViewSocket {
ws.map(transform_rx)
.with(transform_tx)
.sink_map_err(|_| LiveViewError::SendingFailed)
}
fn transform_rx(message: Result<Message, salvo::Error>) -> Result<String, LiveViewError> {
let as_bytes = message.map_err(|_| LiveViewError::SendingFailed)?;
let msg = String::from_utf8(as_bytes.into_bytes()).map_err(|_| LiveViewError::SendingFailed)?;
Ok(msg)
}
async fn transform_tx(message: String) -> Result<Message, salvo::Error> {
Ok(Message::text(message))
}
@@ -0,0 +1,28 @@
use crate::{LiveViewError, LiveViewSocket};
use futures_util::{SinkExt, StreamExt};
use warp::ws::{Message, WebSocket};
/// Convert a warp websocket into a LiveViewSocket
///
/// This is required to launch a LiveView app using the warp web framework
pub fn warp_socket(ws: WebSocket) -> impl LiveViewSocket {
ws.map(transform_rx)
.with(transform_tx)
.sink_map_err(|_| LiveViewError::SendingFailed)
}
fn transform_rx(message: Result<Message, warp::Error>) -> Result<String, LiveViewError> {
// destructure the message into the buffer we got from warp
let msg = message
.map_err(|_| LiveViewError::SendingFailed)?
.into_bytes();
// transform it back into a string, saving us the allocation
let msg = String::from_utf8(msg).map_err(|_| LiveViewError::SendingFailed)?;
Ok(msg)
}
async fn transform_tx(message: String) -> Result<Message, warp::Error> {
Ok(Message::text(message))
}