zino_channel/
cloud_event.rsuse serde::{Deserialize, Serialize};
use zino_core::{datetime::DateTime, JsonValue, Map, SharedString};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(default)]
pub struct CloudEvent<T = ()> {
#[serde(rename = "specversion")]
spec_version: SharedString,
id: String,
source: String,
#[serde(rename = "type")]
event_type: SharedString,
#[serde(rename = "time")]
timestamp: DateTime,
#[serde(skip_serializing_if = "JsonValue::is_null")]
data: JsonValue,
#[serde(rename = "datacontenttype")]
data_content_type: Option<SharedString>,
#[serde(rename = "dataschema")]
data_schema: Option<SharedString>,
#[serde(skip_serializing_if = "Option::is_none")]
subject: Option<SharedString>,
#[serde(rename = "sessionid")]
#[serde(skip_serializing_if = "Option::is_none")]
session_id: Option<String>,
#[serde(flatten)]
extensions: T,
}
impl<T: Default> CloudEvent<T> {
#[inline]
pub fn new(
id: impl ToString,
source: impl ToString,
event_type: impl Into<SharedString>,
) -> Self {
Self {
spec_version: "1.0".into(),
id: id.to_string(),
source: source.to_string(),
event_type: event_type.into(),
timestamp: DateTime::now(),
data: JsonValue::Null,
data_content_type: None,
data_schema: None,
subject: None,
session_id: None,
extensions: T::default(),
}
}
}
impl<T> CloudEvent<T> {
#[inline]
pub fn set_data(&mut self, data: impl Into<JsonValue>) {
self.data = data.into();
}
#[inline]
pub fn set_subject(&mut self, subject: impl Into<SharedString>) {
self.subject = Some(subject.into());
}
#[inline]
pub fn set_session_id(&mut self, session_id: impl ToString) {
self.session_id = Some(session_id.to_string());
}
#[inline]
pub fn id(&self) -> &str {
self.id.as_str()
}
#[inline]
pub fn source(&self) -> &str {
self.source.as_str()
}
#[inline]
pub fn event_type(&self) -> &str {
self.event_type.as_ref()
}
#[inline]
pub fn subject(&self) -> Option<&str> {
self.subject.as_deref()
}
#[inline]
pub fn session_id(&self) -> Option<&str> {
self.session_id.as_deref()
}
#[inline]
pub fn stringify_data(&self) -> String {
self.data.to_string()
}
}
impl<T: Serialize> CloudEvent<T> {
#[must_use]
pub fn into_map(self) -> Map {
match serde_json::to_value(self) {
Ok(JsonValue::Object(map)) => map,
_ => panic!("the cloud event cann't be converted to a json object"),
}
}
}