use std::ops::Deref;
use async_trait::async_trait;
use uuid::Uuid;
use crate::store::StoreEvent;
use crate::Aggregate;
#[async_trait]
pub trait EventHandler<A>: Sync
where
A: Aggregate,
{
async fn handle(&self, event: &StoreEvent<A::Event>);
async fn delete(&self, _aggregate_id: Uuid) {}
fn name(&self) -> &'static str {
std::any::type_name::<Self>()
}
}
#[async_trait]
impl<A, Q, T> EventHandler<A> for T
where
A: Aggregate,
A::Event: Send + Sync,
Q: EventHandler<A>,
T: Deref<Target = Q> + Clone + Send + Sync,
{
async fn handle(&self, event: &StoreEvent<A::Event>) {
self.deref().handle(event).await;
}
async fn delete(&self, aggregate_id: Uuid) {
self.deref().delete(aggregate_id).await;
}
fn name(&self) -> &'static str {
self.deref().name()
}
}
#[async_trait]
pub trait TransactionalEventHandler<A, Er, Ex>: Sync
where
A: Aggregate,
{
async fn handle(&self, event: &StoreEvent<A::Event>, executor: &mut Ex) -> Result<(), Er>;
async fn delete(&self, _aggregate_id: Uuid, _executor: &mut Ex) -> Result<(), Er> {
Ok(())
}
fn name(&self) -> &'static str {
std::any::type_name::<Self>()
}
}
#[async_trait]
impl<A, Er, Ex, Q, T> TransactionalEventHandler<A, Er, Ex> for T
where
A: Aggregate,
A::Event: Send + Sync,
Ex: Send,
Q: TransactionalEventHandler<A, Er, Ex>,
T: Deref<Target = Q> + Send + Sync,
{
async fn handle(&self, event: &StoreEvent<A::Event>, executor: &mut Ex) -> Result<(), Er> {
self.deref().handle(event, executor).await
}
async fn delete(&self, aggregate_id: Uuid, executor: &mut Ex) -> Result<(), Er> {
self.deref().delete(aggregate_id, executor).await
}
fn name(&self) -> &'static str {
self.deref().name()
}
}
pub trait ReplayableEventHandler<A>: Sync
where
Self: EventHandler<A>,
A: Aggregate,
{
}