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 a connect_error event is sent.
    • for MessageHandler: extracts and deserialize to json the message data
  • TryData: extracts and deserialize to json any data but with a Result type in case of error:
  • SocketRef: extracts a reference to the Socket
  • SocketIo: 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 argument
  • 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 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 server

Structs§

  • 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 tracing feature is enabled.
  • 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.
  • It was impossible to find the given extension.
  • 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.
  • An Extractor that returns a clone extension from the request parts if it exists.
  • 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.
  • It 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.