use serde::{Deserialize, Serialize};
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::Hash;
pub trait EventTrait: Clone + Debug + PartialEq + Eq + Hash + Send + Sync + 'static {
fn event_type(&self) -> &str;
fn payload(&self) -> Option<&serde_json::Value>;
fn name(&self) -> &str;
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash, Default)]
pub struct Event {
#[serde(rename = "type")]
#[serde(default)]
pub event_type: String,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] pub payload: Option<serde_json::Value>,
}
impl Event {
pub fn new(event_type: &str) -> Self {
Self {
event_type: event_type.to_string(),
payload: None,
}
}
pub fn with_payload(event_type: &str, payload: serde_json::Value) -> Self {
Self {
event_type: event_type.to_string(),
payload: Some(payload),
}
}
pub fn payload_mut(&mut self) -> Option<&mut serde_json::Value> {
self.payload.as_mut()
}
}
impl EventTrait for Event {
fn event_type(&self) -> &str {
&self.event_type
}
fn payload(&self) -> Option<&serde_json::Value> {
self.payload.as_ref()
}
fn name(&self) -> &str {
&self.event_type
}
}
impl Display for Event {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match &self.payload {
Some(_payload) => write!(f, "{}(...)", self.event_type),
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 From<&str> for Event {
fn from(s: &str) -> Self {
Event::new(s)
}
}
impl IntoEvent for String {
fn into_event(self) -> Event {
Event::new(&self)
}
}
pub const WILDCARD_EVENT: &str = "*";