1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
use std::marker::PhantomData;

use crate::application::{repository, DomainEventHandler, ReadRepository, Repository};
use crate::domain::{AggregateRoot, Entity};

/// A [Repository] implementation that handles [DomainEvent](crate::domain::DomainEvent)s when
/// persisting the [AggregateRoot] entity.
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, RwLock};
///
/// use ddd_rs::application::{
///     domain_event_handler::{self, DomainEventHandler},
///     Repository,
/// };
/// use ddd_rs::domain::{AggregateRoot, Entity, UnitDomainEvent};
/// use ddd_rs::infrastructure::{DomainRepository, InMemoryRepository};
///
/// #[derive(ddd_rs::AggregateRoot, ddd_rs::Entity, Clone)]
/// struct MyEntity {
///     id: i32,
///     domain_events: Vec<UnitDomainEvent>,
///     created_at: chrono::DateTime<chrono::Utc>,
///     updated_at: chrono::DateTime<chrono::Utc>,
/// }
///
/// impl MyEntity {
///     pub fn new(id: i32) -> Self {
///         Self {
///             id,
///             domain_events: vec![],
///             created_at: chrono::Utc::now(),
///             updated_at: chrono::Utc::now(),
///         }
///     }
/// }
///
/// struct MockDomainEventHandler {
///     calls: Arc<RwLock<i32>>,
/// }
///
/// impl MockDomainEventHandler {
///     pub fn new(calls: Arc<RwLock<i32>>) -> Self {
///         Self { calls }
///     }
/// }
///
/// #[async_trait::async_trait]
/// impl DomainEventHandler<UnitDomainEvent> for MockDomainEventHandler {
///     async fn handle(&self, _event: UnitDomainEvent) -> domain_event_handler::Result<()> {
///         let mut calls = self.calls.write().unwrap();
///         *calls += 1;
///
///         Ok(())
///     }
/// }
///
/// # tokio_test::block_on(async {
/// let calls = Arc::new(RwLock::new(0));
///
/// let my_entity_repository = DomainRepository::new(
///     InMemoryRepository::new(),
///     MockDomainEventHandler::new(calls.clone()),
/// );
///
/// let mut my_entity = MyEntity::new(1);
///
/// my_entity.register_domain_event(UnitDomainEvent);
/// my_entity.register_domain_event(UnitDomainEvent);
/// my_entity.register_domain_event(UnitDomainEvent);
///
/// my_entity_repository.add(my_entity).await.unwrap();
///
/// let calls = *calls.read().unwrap();
///
/// assert_eq!(calls, 3);
/// # })
/// ```
pub struct DomainRepository<
    T: AggregateRoot + Send + 'static,
    TRepository: Repository<T>,
    TDomainEventHandler: DomainEventHandler<<T as AggregateRoot>::DomainEvent>,
> {
    aggregate_root_type: PhantomData<T>,
    repository: TRepository,
    domain_event_handler: TDomainEventHandler,
}

impl<
        T: AggregateRoot,
        TRepository: Repository<T>,
        TDomainEventHandler: DomainEventHandler<<T as AggregateRoot>::DomainEvent>,
    > DomainRepository<T, TRepository, TDomainEventHandler>
{
    /// Creates a new [DomainRepository].
    pub fn new(repository: TRepository, domain_event_handler: TDomainEventHandler) -> Self {
        Self {
            aggregate_root_type: PhantomData,
            repository,
            domain_event_handler,
        }
    }
}

#[async_trait::async_trait]
impl<
        T: AggregateRoot,
        TRepository: Repository<T>,
        TDomainEventHandler: DomainEventHandler<<T as AggregateRoot>::DomainEvent>,
    > Repository<T> for DomainRepository<T, TRepository, TDomainEventHandler>
{
    async fn add(&self, mut entity: T) -> repository::Result<T> {
        let domain_events = entity.drain_domain_events();

        let result = self.repository.add(entity).await?;

        for event in domain_events.into_iter() {
            self.domain_event_handler.handle(event).await?;
        }

        Ok(result)
    }

    async fn update(&self, mut entity: T) -> repository::Result<T> {
        let domain_events = entity.drain_domain_events();

        let result = self.repository.update(entity).await?;

        for event in domain_events.into_iter() {
            self.domain_event_handler.handle(event).await?;
        }

        Ok(result)
    }

    async fn delete(&self, mut entity: T) -> repository::Result<()> {
        let domain_events = entity.drain_domain_events();

        let result = self.repository.delete(entity).await?;

        for event in domain_events.into_iter() {
            self.domain_event_handler.handle(event).await?;
        }

        Ok(result)
    }
}

#[async_trait::async_trait]
impl<
        T: AggregateRoot,
        TRepository: Repository<T>,
        TDomainEventHandler: DomainEventHandler<<T as AggregateRoot>::DomainEvent>,
    > ReadRepository<T> for DomainRepository<T, TRepository, TDomainEventHandler>
{
    async fn get_by_id(&self, id: <T as Entity>::Id) -> repository::Result<Option<T>> {
        self.repository.get_by_id(id).await
    }

    async fn list(&self, skip: usize, take: usize) -> repository::Result<Vec<T>> {
        self.repository.list(skip, take).await
    }

    async fn count(&self) -> repository::Result<usize> {
        self.repository.count().await
    }
}