Expand description
§Extractors for ConnectHandler, ConnectMiddleware, MessageHandler and DisconnectHandler.
They can be used to extract data from the context of the handler and get specific params. Here are some examples of extractors:
Data: extracts and deserialize from any receieved data, if a deserialization error occurs the handler won’t be called:- for
ConnectHandler: extracts and deserialize from the incoming auth data - for
ConnectMiddleware: extract and deserialize from the incoming auth data. In case of error, the middleware chain stops and aconnect_errorevent is sent. - for
MessageHandler: extracts and deserialize from the incoming message data
- for
TryData: extracts and deserialize from the any received data but with aResulttype in case of error:- for
ConnectHandlerandConnectMiddleware: extracts and deserialize from the incoming auth data - for
MessageHandler: extracts and deserialize from the incoming message data
- for
Event: extracts the message event name.SocketRef: extracts a reference to theSocket.SocketIo: extracts a reference to the whole socket.io server context.AckSender: Can be used to send an ack response to the current message event.ProtocolVersion: extracts the protocol version.TransportType: extracts the transport type.DisconnectReason: extracts the reason of the disconnection.State: extracts aCloneof a state previously set withSocketIoBuilder::with_state.Extension: extracts an extension of the given type stored on the called socket by cloning it.MaybeExtension: extracts an extension of the given type if it exists orNoneotherwise.HttpExtension: extracts an http extension of the given type coming from the request (Similar to axum’sextract::Extension.MaybeHttpExtension: extracts an http extension of the given type if it exists orNoneotherwise.
§You can also implement your own Extractor!
Implement the FromConnectParts, FromMessageParts, FromMessage and FromDisconnectParts traits
on any type to extract data from the context of the handler.
When implementing these traits, if you clone the Arc<Socket> make sure
that it is dropped at least when the socket is disconnected.
Otherwise it will create a memory leak. It is why the SocketRef extractor is used instead of cloning
the socket for common usage.
If you want to deserialize the Value data you must manually call
the Data extractor to deserialize it.
§Example that extracts a user id from the query params
struct UserId(String);
#[derive(Debug)]
struct UserIdNotFound;
impl std::fmt::Display for UserIdNotFound {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "User id not found")
}
}
impl std::error::Error for UserIdNotFound {}
impl<A: Adapter> FromConnectParts<A> for UserId {
type Error = Infallible;
fn from_connect_parts(s: &Arc<Socket<A>>, _: &Option<Value>) -> Result<Self, Self::Error> {
// In a real app it would be better to parse the query params with a crate like `url`
let uri = &s.req_parts().uri;
let uid = uri
.query()
.and_then(|s| s.split('&').find(|s| s.starts_with("id=")).map(|s| &s[3..]))
.unwrap_or_default();
// Currently, it is not possible to have lifetime on the extracted data
Ok(UserId(uid.to_string()))
}
}
// Here, if the user id is not found, the handler won't be called
// and a tracing `error` log will be emitted (if the `tracing` feature is enabled)
impl<A: Adapter> FromMessageParts<A> for UserId {
type Error = UserIdNotFound;
fn from_message_parts(s: &Arc<Socket<A>>, _: &mut Value, _: &Option<i64>) -> Result<Self, UserIdNotFound> {
// In a real app it would be better to parse the query params with a crate like `url`
let uri = &s.req_parts().uri;
let uid = uri
.query()
.and_then(|s| s.split('&').find(|s| s.starts_with("id=")).map(|s| &s[3..]))
.ok_or(UserIdNotFound)?;
// Currently, it is not possible to have lifetime on the extracted data
Ok(UserId(uid.to_string()))
}
}
async fn handler(user_id: UserId) {
println!("User id: {}", user_id.0);
}
let (svc, io) = SocketIo::new_svc();
io.ns("/", handler);
// Use the service with your favorite http serverStructs§
- AckSender
- An Extractor to send an ack response corresponding to the current event. If the client sent a normal message without expecting an ack, the ack callback will do nothing.
- Data
- An Extractor that returns the deserialized data without checking errors.
If a deserialization error occurs, the handler won’t be called
and an error log will be printed if the
tracingfeature is enabled. - Event
- An Extractor that returns the event name related to the incoming message.
- Extension
extensions - An Extractor that returns the extension of the given type.
If the extension is not found,
the handler won’t be called and an error log will be print if the
tracingfeature is enabled. - Extension
NotFound - It was impossible to find the given extension.
- Http
Extension - An Extractor that returns a clone extension from the request parts.
- Maybe
Extension extensions - An Extractor that returns the extension of the given type T if it exists or
Noneotherwise. - Maybe
Http Extension - An Extractor that returns a clone extension from the request parts if it exists.
- Socket
Ref - An Extractor that returns a reference to a
Socket. - State
state - An Extractor that contains a
Cloneof a state previously set withSocketIoBuilder::with_state. It implementsstd::ops::Derefto access the inner type so you can use it as a normal reference. - State
NotFound state - It was impossible to find the given state and therefore the handler won’t be called.
- TryData
- An Extractor that returns the deserialized incoming data or a deserialization error.