warp_adapter.rs 942 B

12345678910111213141516171819202122232425262728
  1. use crate::{LiveViewError, LiveViewSocket};
  2. use futures_util::{SinkExt, StreamExt};
  3. use warp::ws::{Message, WebSocket};
  4. /// Convert a warp websocket into a LiveViewSocket
  5. ///
  6. /// This is required to launch a LiveView app using the warp web framework
  7. pub fn warp_socket(ws: WebSocket) -> impl LiveViewSocket {
  8. ws.map(transform_rx)
  9. .with(transform_tx)
  10. .sink_map_err(|_| LiveViewError::SendingFailed)
  11. }
  12. fn transform_rx(message: Result<Message, warp::Error>) -> Result<String, LiveViewError> {
  13. // destructure the message into the buffer we got from warp
  14. let msg = message
  15. .map_err(|_| LiveViewError::SendingFailed)?
  16. .into_bytes();
  17. // transform it back into a string, saving us the allocation
  18. let msg = String::from_utf8(msg).map_err(|_| LiveViewError::SendingFailed)?;
  19. Ok(msg)
  20. }
  21. async fn transform_tx(message: String) -> Result<Message, warp::Error> {
  22. Ok(Message::text(message))
  23. }