1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
//! ## A tower [`Layer`] for socket.io so it can be used as a middleware with frameworks supporting layers.
//!
//! #### Example with axum :
//! ```rust
//! # use socketioxide::SocketIo;
//! # use axum::routing::get;
//! // Create a socket.io layer
//! let (layer, io) = SocketIo::new_layer();
//!
//! // Add io namespaces and events...
//!
//! let app = axum::Router::<()>::new()
//! .route("/", get(|| async { "Hello, World!" }))
//! .layer(layer);
//!
//! // Spawn axum server
//!
//! ```
//!
//! #### Example with salvo :
//! ```no_run
//! # use salvo::prelude::*;
//! # use socketioxide::SocketIo;
//!
//! #[handler]
//! async fn hello() -> &'static str {
//! "Hello World"
//! }
//! // Create a socket.io layer
//! let (layer, io) = SocketIo::new_layer();
//!
//! // Add io namespaces and events...
//!
//! let layer = layer.compat();
//! let router = Router::with_path("/socket.io").hoop(layer).goal(hello);
//! // Spawn salvo server
//! ```
use std::sync::Arc;
use tower::Layer;
use crate::{
adapter::{Adapter, LocalAdapter},
client::Client,
service::SocketIoService,
SocketIoConfig,
};
/// A [`Layer`] for [`SocketIoService`], acting as a middleware.
pub struct SocketIoLayer<A: Adapter = LocalAdapter> {
client: Arc<Client<A>>,
}
impl<A: Adapter> Clone for SocketIoLayer<A> {
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
}
}
}
impl<A: Adapter> SocketIoLayer<A> {
pub(crate) fn from_config(config: Arc<SocketIoConfig>) -> (Self, Arc<Client<A>>) {
let client = Arc::new(Client::new(config.clone()));
let layer = Self {
client: client.clone(),
};
(layer, client)
}
}
impl<S: Clone, A: Adapter> Layer<S> for SocketIoLayer<A> {
type Service = SocketIoService<S, A>;
fn layer(&self, inner: S) -> Self::Service {
SocketIoService::with_client(inner, self.client.clone())
}
}