event_store_adapter_rs/
serializer.rs1use crate::types::{Aggregate, Event, EventStoreReadError, EventStoreWriteError};
2use std::fmt::Debug;
3
4pub trait EventSerializer<E: Event>: Debug + Send + Sync + 'static {
5 fn serialize(&self, event: &E) -> Result<Vec<u8>, EventStoreWriteError>;
6 fn deserialize(&self, data: &[u8]) -> Result<Box<E>, EventStoreReadError>;
7}
8
9#[derive(Debug)]
10pub struct JsonEventSerializer<E: Event> {
11 _phantom: std::marker::PhantomData<E>,
12}
13
14impl<E: Event> Default for JsonEventSerializer<E> {
15 fn default() -> Self {
16 JsonEventSerializer {
17 _phantom: std::marker::PhantomData,
18 }
19 }
20}
21
22impl<E: Event> EventSerializer<E> for JsonEventSerializer<E> {
23 fn serialize(&self, event: &E) -> Result<Vec<u8>, EventStoreWriteError> {
24 serde_json::to_vec(event).map_err(|e| EventStoreWriteError::SerializationError(e.into()))
25 }
26
27 fn deserialize(&self, data: &[u8]) -> Result<Box<E>, EventStoreReadError> {
28 serde_json::from_slice(data)
29 .map_err(|e| EventStoreReadError::DeserializationError(e.into()))
30 .map(Box::new)
31 }
32}
33
34pub trait SnapshotSerializer<A: Aggregate>: Debug + Send + Sync + 'static {
35 fn serialize(&self, aggregate: &A) -> Result<Vec<u8>, EventStoreWriteError>;
36 fn deserialize(&self, data: &[u8]) -> Result<Box<A>, EventStoreReadError>;
37}
38
39#[derive(Debug)]
40pub struct JsonSnapshotSerializer<A: Aggregate> {
41 _phantom: std::marker::PhantomData<A>,
42}
43
44impl<A: Aggregate> Default for JsonSnapshotSerializer<A> {
45 fn default() -> Self {
46 JsonSnapshotSerializer {
47 _phantom: std::marker::PhantomData,
48 }
49 }
50}
51
52impl<A: Aggregate> SnapshotSerializer<A> for JsonSnapshotSerializer<A> {
53 fn serialize(&self, aggregate: &A) -> Result<Vec<u8>, EventStoreWriteError> {
54 serde_json::to_vec(aggregate).map_err(|e| EventStoreWriteError::SerializationError(e.into()))
55 }
56
57 fn deserialize(&self, data: &[u8]) -> Result<Box<A>, EventStoreReadError> {
58 serde_json::from_slice(data)
59 .map_err(|e| EventStoreReadError::DeserializationError(e.into()))
60 .map(Box::new)
61 }
62}