Module socketioxide::extract
source · 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 to json any data, if a deserialization error occurs the handler won’t be called:- for
ConnectHandler: extracts and deserialize to json the auth data - for
ConnectMiddleware: extract and deserialize to json the auth data. In case of error, the middleware chain stops and aconnect_errorevent is sent. - for
MessageHandler: extracts and deserialize to json the message data
- for
TryData: extracts and deserialize to json any data but with aResulttype in case of error:- for
ConnectHandlerandConnectMiddleware: extracts and deserialize to json the auth data - for
MessageHandler: extracts and deserialize to json the message data
- for
SocketRef: extracts a reference to theSocketSocketIo: extracts a reference to the whole socket.io server context.Bin: extract a binary payload for a given message. Because it consumes the event it should be the last argumentAckSender: Can be used to send an ack response to the current message eventProtocolVersion: extracts the protocol versionTransportType: extracts the transport typeDisconnectReason: extracts the reason of the disconnectionState: 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 orNoneotherwiseHttpExtension: extracts an http extension of the given type coming from the request. (Similar to axum’sextract::ExtensionMaybeHttpExtension: extracts an http extension of the given type if it exists orNoneotherwise.
§You can also implement your own Extractor with the FromConnectParts, FromMessageParts and FromDisconnectParts traits
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.
§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<String>) -> 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 serde_json::Value,
_: &mut Vec<Bytes>,
_: &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()))
}
}
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§
- 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.
- An Extractor that returns the binary data of the message. If there is no binary data, it will contain an empty vec.
- 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 print if the
tracingfeature is enabled. - Extension
extensionsAn 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 thetracingfeature is enabled. - It was impossible to find the given extension.
- An Extractor that returns a clone extension from the request parts.
- Maybe
Extension extensionsAn Extractor that returns the extension of the given type T if it exists orNoneotherwise. - An Extractor that returns a clone extension from the request parts if it exists.
- An Extractor that returns a reference to a
Socket. - State
stateAn Extractor that contains aCloneof 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 stateIt was impossible to find the given state and therefore the handler won’t be called. - An Extractor that returns the deserialized data related to the event.