Module extract

Module 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 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 a connect_error event is sent.
    • for MessageHandler: extracts and deserialize from the incoming message data
  • TryData: extracts and deserialize from the any received data but with a Result type in case of error:
  • Event: extracts the message event name.
  • SocketRef: extracts a reference to the Socket.
  • 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 a Clone of a state previously set with SocketIoBuilder::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 or None otherwise.
  • HttpExtension: extracts an http extension of the given type coming from the request (Similar to axum’s extract::Extension.
  • MaybeHttpExtension: extracts an http extension of the given type if it exists or None otherwise.

§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 server

Structs§

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 tracing feature is enabled.
Event
An Extractor that returns the event name related to the incoming message.
Extensionextensions
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 tracing feature is enabled.
ExtensionNotFound
It was impossible to find the given extension.
HttpExtension
An Extractor that returns a clone extension from the request parts.
MaybeExtensionextensions
An Extractor that returns the extension of the given type T if it exists or None otherwise.
MaybeHttpExtension
An Extractor that returns a clone extension from the request parts if it exists.
SocketRef
An Extractor that returns a reference to a Socket.
Statestate
An Extractor that contains a Clone of a state previously set with SocketIoBuilder::with_state. It implements std::ops::Deref to access the inner type so you can use it as a normal reference.
StateNotFoundstate
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.