use serde::{Deserialize, Serialize};
use std::fmt;
pub trait EventTrait {
fn event_type(&self) -> &str;
fn payload(&self) -> Option<&serde_json::Value>;
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Event {
pub event_type: String,
pub payload: Option<serde_json::Value>,
}
impl Event {
pub fn new(event_type: impl Into<String>) -> Self {
Self {
event_type: event_type.into(),
payload: None,
}
}
pub fn with_payload(
event_type: impl Into<String>,
payload: impl Into<serde_json::Value>,
) -> Self {
Self {
event_type: event_type.into(),
payload: Some(payload.into()),
}
}
}
impl EventTrait for Event {
fn event_type(&self) -> &str {
&self.event_type
}
fn payload(&self) -> Option<&serde_json::Value> {
self.payload.as_ref()
}
}
impl fmt::Display for Event {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.payload {
Some(payload) => write!(f, "{}({})", self.event_type, payload),
None => write!(f, "{}", self.event_type),
}
}
}
pub trait IntoEvent {
fn into_event(self) -> Event;
}
impl IntoEvent for Event {
fn into_event(self) -> Event {
self
}
}
impl IntoEvent for &str {
fn into_event(self) -> Event {
Event::new(self)
}
}
impl IntoEvent for String {
fn into_event(self) -> Event {
Event::new(self)
}
}
impl IntoEvent for &String {
fn into_event(self) -> Event {
Event::new(self)
}
}
pub const WILDCARD_EVENT: &str = "*";