diff --git a/src/gateway/backends/mod.rs b/src/gateway/backends/mod.rs index 53123fe..fe6e325 100644 --- a/src/gateway/backends/mod.rs +++ b/src/gateway/backends/mod.rs @@ -1,9 +1,22 @@ -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(not(target_arch = "wasm32"), feature = "client"))] pub mod tungstenite; +#[cfg(all(not(target_arch = "wasm32"), feature = "client"))] +pub use tungstenite::*; +#[cfg(all(target_arch = "wasm32", feature = "client"))] +pub mod wasm; +#[cfg(all(target_arch = "wasm32", feature = "client"))] +pub use wasm::*; -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(not(target_arch = "wasm32"), feature = "client"))] pub type Sink = tungstenite::TungsteniteSink; -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(not(target_arch = "wasm32"), feature = "client"))] pub type Stream = tungstenite::TungsteniteStream; -#[cfg(not(target_arch = "wasm32"))] +#[cfg(all(not(target_arch = "wasm32"), feature = "client"))] pub type WebSocketBackend = tungstenite::TungsteniteBackend; + +#[cfg(all(target_arch = "wasm32", feature = "client"))] +pub type Sink = wasm::WasmSink; +#[cfg(all(target_arch = "wasm32", feature = "client"))] +pub type Stream = wasm::WasmStream; +#[cfg(all(target_arch = "wasm32", feature = "client"))] +pub type WebSocketBackend = wasm::WasmBackend; diff --git a/src/gateway/backends/wasm.rs b/src/gateway/backends/wasm.rs new file mode 100644 index 0000000..546a05d --- /dev/null +++ b/src/gateway/backends/wasm.rs @@ -0,0 +1,46 @@ +use futures_util::{ + stream::{SplitSink, SplitStream}, + StreamExt, +}; + +use ws_stream_wasm::*; + +use crate::errors::GatewayError; +use crate::gateway::GatewayMessage; + +#[derive(Debug, Clone)] +pub struct WasmBackend; + +// These could be made into inherent associated types when that's stabilized +pub type WasmSink = SplitSink>, tungstenite::Message>; +pub type WasmStream = SplitStream>>; + +impl WasmBackend { + pub async fn connect( + websocket_url: &str, + ) -> Result<(WasmSink, WasmStream), crate::errors::GatewayError> { + let (websocket_stream, _) = match WsMeta::connect(); + { + Ok(websocket_stream) => websocket_stream, + Err(e) => { + return Err(GatewayError::CannotConnect { + error: e.to_string(), + }) + } + }; + + Ok(websocket_stream.split()) + } +} + +impl From for WsMessage { + fn from(message: GatewayMessage) -> Self { + Self::Text(message.0) + } +} + +impl From for GatewayMessage { + fn from(value: WsMessage) -> Self { + Self(value.to_string()) + } +}