intrepid-core 0.1.6

Manage complex async business logic with ease
Documentation
use crate::{Context, Frame};

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

/// Extracts a JSON-serializable type from a message frame's meta.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MessageMetaJson<T>(pub T);

impl<T, State> Extractor<State> for MessageMetaJson<T>
where
    T: serde::de::DeserializeOwned,
{
    type Error = MessageFrameError;

    fn extract(frame: Frame, context: &Context<State>) -> Result<Self, Self::Error>
    where
        Self: Sized,
    {
        let Message(message_frame) = Message::extract(frame, context)?;
        let contents: T = serde_json::from_slice(&message_frame.meta)
            .map_err(MessageFrameError::MalformedJsonMeta)?;

        Ok(Self(contents))
    }
}

#[test]
fn message_meta_json() -> crate::Result<()> {
    let json = serde_json::to_vec(&vec![1, 2, 3]).expect("Couldn't make a byte vec");
    let frame = Frame::message("/test", (), json);
    let context = Context::<()>::default();
    let MessageMetaJson(message_meta) =
        MessageMetaJson::<Vec<usize>>::extract_from_frame_and_state(frame, &context)?;

    assert_eq!(message_meta, vec![1, 2, 3]);

    Ok(())
}

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

    let context = Context::<()>::default();
    let result =
        MessageMetaJson::<Vec<usize>>::extract_from_frame_and_state(Frame::default(), &context);

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

    Ok(())
}

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

    let frame = Frame::message("/test", (), vec![1, 2, 3]);
    let context = Context::<()>::default();
    let result = MessageMetaJson::<Vec<usize>>::extract_from_frame_and_state(frame, &context);

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

    Ok(())
}