Class: Dry::Facts::EventStore::InMemoryFactStore

Inherits:
Object
  • Object
show all
Defined in:
lib/dry/facts/event_store.rb

Instance Method Summary collapse

Constructor Details

#initializeInMemoryFactStore

Returns a new instance of InMemoryFactStore.



6
7
8
# File 'lib/dry/facts/event_store.rb', line 6

def initialize
  @serialized_events = []
end

Instance Method Details

#aggregate_from_event(klass, event) ⇒ Object



10
11
12
13
14
15
# File 'lib/dry/facts/event_store.rb', line 10

def aggregate_from_event(klass, event)
  get_events_by_key(
    key:    :aggregate_id,
    value:  event.to_h[:data][:aggregate_id])
  .yield_self {|events| klass.new(events)}
end

#deserialize_event(serialized_event) ⇒ Object



49
50
51
52
53
# File 'lib/dry/facts/event_store.rb', line 49

def deserialize_event(serialized_event)
  Event
  .from_h(serialized_event)
  .freeze
end

#get_event_by_id(fact_id) ⇒ Object

get_event_by_id(42)



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/dry/facts/event_store.rb', line 25

def get_event_by_id(fact_id)
  # fail if event_id nil?
  # fail if no events found?
  # fail if many events found?
  @serialized_events
  .find_all   {|f|  fact_id == (f && f[:metadata] && f[:metadata][:id])}
  .yield_self {|it| (0 == it.length) ? fail("No fact found") : it }
  .yield_self {|it| (1 <  it.length) ? fail("Too may facts") : it }
  .first
  .yield_self {|it| deserialize_event(it)}
end

#get_events_by_key(key:, value:) ⇒ Object

get_events_by_key(key: ‘aggregate-id’, value: 42)



38
39
40
41
42
# File 'lib/dry/facts/event_store.rb', line 38

def get_events_by_key(key:, value:)
  @serialized_events
  .find_all   {|f|  value == f[key]}
  .map        {|it| deserialize_event(it)}
end

#persist_event_and_return(event) ⇒ Object

persist_event_and_return(event)



18
19
20
21
22
# File 'lib/dry/facts/event_store.rb', line 18

def persist_event_and_return(event)
  # validate & fail
  @serialized_events << event.to_h
  event
end

#serialize_event(fact) ⇒ Object



44
45
46
47
# File 'lib/dry/facts/event_store.rb', line 44

def serialize_event(fact)
  fact
  .to_h
end