use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum InAppSeverity {
Info,
Success,
Warning,
Error,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InAppMessage {
pub notification_type: String,
pub data: serde_json::Value,
pub severity: Option<InAppSeverity>,
}
impl InAppMessage {
pub fn new(notification_type: impl Into<String>) -> Self {
Self {
notification_type: notification_type.into(),
data: serde_json::Value::Null,
severity: None,
}
}
pub fn data(mut self, data: serde_json::Value) -> Self {
self.data = data;
self
}
pub fn severity(mut self, level: InAppSeverity) -> Self {
self.severity = Some(level);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_in_app_message_builder() {
let msg = InAppMessage::new("OrderShipped")
.data(serde_json::json!({"order_id": 42}))
.severity(InAppSeverity::Success);
assert_eq!(msg.notification_type, "OrderShipped");
assert_eq!(msg.data, serde_json::json!({"order_id": 42}));
assert_eq!(msg.severity, Some(InAppSeverity::Success));
}
#[test]
fn test_in_app_severity_serialization() {
for (level, expected) in &[
(InAppSeverity::Info, "\"info\""),
(InAppSeverity::Success, "\"success\""),
(InAppSeverity::Warning, "\"warning\""),
(InAppSeverity::Error, "\"error\""),
] {
let json = serde_json::to_string(level).unwrap();
assert_eq!(&json, expected);
}
}
}