intrepid-core 0.1.2

Manage complex async business logic with ease
Documentation
use bytes::Bytes;

use super::{ExtractContext, Extractor, Message, MessageFrameError};

/// Extract the raw metadata of a message from a frame. This gives you the
/// unprocessed metadata of the message in [`Bytes`] form. Other parts of
/// the system presume JSON encoding and things like that, but this
/// will let you determine what format you like.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MessageMeta(pub Bytes);

impl<State> Extractor<State> for MessageMeta {
    type Error = MessageFrameError;

    fn extract(frame: crate::Frame, context: &ExtractContext<State>) -> Result<Self, Self::Error>
    where
        Self: Sized,
    {
        let Message(message_frame) = Message::extract(frame, context)?;

        Ok(Self(message_frame.meta))
    }
}

#[test]
fn raw_message_meta() -> Result<(), MessageFrameError> {
    use crate::{ActionContext, Frame};

    let frame = Frame::message("/test", (), "42".to_string());
    let context = (ActionContext::default(), ());
    let MessageMeta(message_meta) = MessageMeta::extract(frame, &context)?;

    assert_eq!(message_meta, Bytes::from("42".to_string()));

    Ok(())
}

#[test]
fn failure() -> Result<(), MessageFrameError> {
    use crate::{ActionContext, Error, ExtractorError, Frame};

    let context = (ActionContext::default(), ());
    let result = MessageMeta::extract_from_frame_and_state(Frame::default(), &context);

    assert!(matches!(
        result.unwrap_err(),
        Error::ExtractorError(ExtractorError::MessageFrameError(
            MessageFrameError::WrongFrame(_)
        ))
    ),);

    Ok(())
}