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
use cqrs_es2::{
    Aggregate,
    AggregateContext,
};

/// Holds context for a pure event store implementation for MemStore
pub struct PostgresSnapshotStoreAggregateContext<A>
where
    A: Aggregate, {
    /// The aggregate ID of the aggregate instance that has been
    /// loaded.
    pub aggregate_id: String,
    /// The current state of the aggregate instance.
    aggregate: A,
    /// The last committed event sequence number for this aggregate
    /// instance.
    pub current_sequence: usize,
}

impl<A> AggregateContext<A>
    for PostgresSnapshotStoreAggregateContext<A>
where
    A: Aggregate,
{
    fn aggregate(&self) -> &A {
        &self.aggregate
    }
}

impl<A> PostgresSnapshotStoreAggregateContext<A>
where
    A: Aggregate,
{
    /// creates a new instance
    pub fn new(
        aggregate_id: String,
        aggregate: A,
        current_sequence: usize,
    ) -> PostgresSnapshotStoreAggregateContext<A> {
        PostgresSnapshotStoreAggregateContext {
            aggregate_id,
            aggregate,
            current_sequence,
        }
    }

    pub(crate) fn aggregate_copy(&self) -> A {
        let ser = serde_json::to_value(&self.aggregate).unwrap();
        serde_json::from_value(ser).unwrap()
    }
}