Class: EventSourcery::Repository

Inherits:
Object
  • Object
show all
Defined in:
lib/event_sourcery/repository.rb

Overview

This class provides a set of methods to help load and save aggregate instances.

Refer to EventSourceryTodoApp for a more complete example.

Examples:

repository = EventSourcery::Repository.new(
  event_source: EventSourceryTodoApp.event_source,
  event_sink: EventSourceryTodoApp.event_sink,
)

aggregate = repository.load(Aggregates::Todo, command.aggregate_id)
aggregate.amend(command.payload)
repository.save(aggregate)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(event_source:, event_sink:) ⇒ Repository

Returns a new instance of Repository.

Parameters:

  • event_source

    event source to be used for loading the events for the aggregate

  • event_sink

    event sink to be used for saving any new events for the aggregate


29
30
31
32
# File 'lib/event_sourcery/repository.rb', line 29

def initialize(event_source:, event_sink:)
  @event_source = event_source
  @event_sink = event_sink
end

Class Method Details

.load(aggregate_class, aggregate_id, event_source:, event_sink:) ⇒ Object

Create a new instance of the repository and load an aggregate instance

Parameters:

  • aggregate_class

    Aggregate type

  • aggregate_id (Integer)

    ID of the aggregate instance to be loaded

  • event_source

    event source to be used for loading the events for the aggregate

  • event_sink

    event sink to be used for saving any new events for the aggregate


22
23
24
25
# File 'lib/event_sourcery/repository.rb', line 22

def self.load(aggregate_class, aggregate_id, event_source:, event_sink:)
  new(event_source: event_source, event_sink: event_sink)
    .load(aggregate_class, aggregate_id)
end

Instance Method Details

#load(aggregate_class, aggregate_id) ⇒ Object

Load an aggregate instance

Parameters:

  • aggregate_class

    Aggregate type

  • aggregate_id (Integer)

    ID of the aggregate instance to be loaded


38
39
40
41
# File 'lib/event_sourcery/repository.rb', line 38

def load(aggregate_class, aggregate_id)
  events = event_source.get_events_for_aggregate_id(aggregate_id)
  aggregate_class.new(aggregate_id, events)
end

#save(aggregate) ⇒ Object

Save any new events/changes in the provided aggregate to the event sink

Parameters:

  • aggregate

    An aggregate instance to be saved


46
47
48
49
50
51
52
53
# File 'lib/event_sourcery/repository.rb', line 46

def save(aggregate)
  new_events = aggregate.changes
  if new_events.any?
    event_sink.sink(new_events,
                    expected_version: aggregate.version - new_events.count)
  end
  aggregate.clear_changes
end