valinor-wire 0.1.0

Wire protocol and message encoding for MudWorld platform
Documentation
use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Error, Debug, PartialEq, Eq)]
pub enum EnvelopeError {
    #[error("invalid envelope format")]
    InvalidFormat,
    #[error("unknown message type: {0}")]
    UnknownType(String),
    #[error("decode error: {0}")]
    Decode(String),
    #[error("encode error: {0}")]
    Encode(String),
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Envelope {
    #[serde(rename = "type")]
    pub msg_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
    pub payload: serde_json::Value,
}

impl Envelope {
    pub fn request(
        msg_type: impl Into<String>,
        request_id: String,
        payload: serde_json::Value,
    ) -> Self {
        Self {
            msg_type: msg_type.into(),
            request_id: Some(request_id),
            payload,
        }
    }

    pub fn event(msg_type: impl Into<String>, payload: serde_json::Value) -> Self {
        Self {
            msg_type: msg_type.into(),
            request_id: None,
            payload,
        }
    }

    pub fn response(request_id: String, payload: serde_json::Value) -> Self {
        Self {
            msg_type: "response".to_string(),
            request_id: Some(request_id),
            payload,
        }
    }

    pub fn error(request_id: Option<String>, code: &str, message: &str) -> Self {
        Self {
            msg_type: "error".to_string(),
            request_id,
            payload: serde_json::json!({
                "code": code,
                "message": message
            }),
        }
    }
}