serverlesstechnology / cqrs

A lightweight, opinionated CQRS and event sourcing framework.
Other
384 stars 42 forks source link

Clone trait implementation for memory store #54

Closed aitoroses closed 1 year ago

aitoroses commented 1 year ago

Hi there!

When I try to test an aggregate by using a MemStore and then trying to load the resulting aggregate I'm having this error:

let event_store = MemStore::<MyAggregate>::default();
let cqrs = CqrsFramework::new(event_store, vec![], services);

cqrs.execute(
    aggregate_id,
    command1,
)
.await
.unwrap();

let aggregate = event_store.load_aggregate(aggregate_id).await.unwrap();
252 |         let event_store = MemStore::<MyAggregate>::default();
    |             ----------- move occurs because `event_store` has type `MemStore<aggregate::MyAggregate>`, which does not implement the `Copy` trait
253 |         let cqrs = CqrsFramework::new(event_store, vec![], Box::new(services));
    |                                       ----------- value moved here
...
272 |         event_store.load_aggregate(aggregate_id).await.unwrap();
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move

I tried to copy the source of MemStore and use derive(Clone), then I can just clone the event_store and it works without any problem.

Is this intentional? or is there another better way to handle this use case?

Thanks!

davegarred commented 1 year ago

Hi @aitoroses,

I think deriving Clone here would be fine, I'll verify this and get it included with the next version.

In the meantime you can use MemStore::get_events(&self) to access to the underlying event map. Example:

  let event_store = MemStore::<MyAggregate>::default();
  let stored_events = event_store.get_events();
  let cqrs = CqrsFramework::new(event_store, vec![], MyService);
  cqrs.execute("test_id", MyCommands::DoSomething).await.unwrap();
  let unlocked_event_map = stored_events.read().unwrap();
  assert_eq!(unlocked_event_map.get("test_id").unwrap().len(), 1);