zero4rs 2.0.0

zero4rs is a powerful, pragmatic, and extremely fast web framework for Rust
Documentation
use serde_json::json;

#[rustfmt::skip]
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, strum_macros::EnumString, )]
#[strum(ascii_case_insensitive)]
pub enum Level {
    Msg,
    Err,
    Info,
    Warn,
}

// message type
#[rustfmt::skip]
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, strum_macros::EnumString, )]
#[strum(ascii_case_insensitive)]
pub enum Ty {
    ServerTime, // 当前服务器时间消息推送
    Connected,  // 连接已建立消息
    Disconnect, // 断开连接消息

    Accept,  // 当前操作已被接受到,等待异步通知
    Success, // 操作成信息
    Failed,  // 失败提示信息

    Notification, // 系统通知信息

    ChatMessage,    // 聊天信息
    HistoryMessage, // 历史聊天记录消息
    HistoryTalk,    // 历史会话消息

    UserOnline,  // 用户上线消息
    UserOffline, // 用户下线消息

    Location,    // 位置信息
}

#[derive(serde::Serialize, serde::Deserialize)]
pub enum TypedMessage {
    TextMessage(String),
    JsonMessage(serde_json::Value),
}

#[derive(serde::Serialize, serde::Deserialize)]
pub struct OutputMessage {
    pub id: Option<String>,
    pub level: Level,
    pub ty: Ty,
    pub msg: Option<String>,
    pub data: Option<serde_json::Value>,
}

impl From<OutputMessage> for bytestring::ByteString {
    fn from(val: OutputMessage) -> Self {
        let json_string = serde_json::to_string(&val).unwrap();
        let byte_string: bytestring::ByteString = bytestring::ByteString::from(json_string);

        byte_string
    }
}

impl OutputMessage {
    pub fn err(ty: Ty, msg: &str, id: Option<String>) -> Self {
        OutputMessage {
            id,
            level: Level::Err,
            ty,
            msg: Some(msg.to_string()),
            data: None,
        }
    }

    pub fn message(&self) -> Option<String> {
        let mut vl = json! ({"level": self.level, "ty": self.ty});

        if let Some(id) = &self.id {
            vl["id"] = json!(id);
        }

        if let Some(data) = &self.data {
            vl["data"] = data.clone();

            // 这里创建一个新的可变 JSON 对象
            if let Some(obj) = vl["data"].as_object_mut() {
                obj.remove("id");
            }
        }

        if let Some(msg) = &self.msg {
            vl["msg"] = json!(msg);
        }

        vl["@ts"] = json!(Self::ts());

        Some(serde_json::to_string(&vl).unwrap())
    }

    pub fn ts() -> String {
        chrono::Utc::now()
            .format("%Y-%m-%dT%H:%M:%S.%3f")
            .to_string()
            + "Z"
    }
}