Class: Akasha::CommandRouter

Inherits:
Object
  • Object
show all
Defined in:
lib/akasha/command_router.rb,
lib/akasha/command_router/optimistic_transactor.rb

Overview

Routes commands to their handlers.

Defined Under Namespace

Classes: OptimisticTransactor

Instance Method Summary collapse

Constructor Details

#initialize(**routes) ⇒ CommandRouter

Returns a new instance of CommandRouter.



9
10
11
# File 'lib/akasha/command_router.rb', line 9

def initialize(**routes)
  @routes = routes
end

Instance Method Details

#register(command, aggregate_class = nil, &block) ⇒ Object

Registers a handler.

As a result, when ‘#route!` is called for that command, the aggregate will be loaded from repository, the command will be sent to the object to invoke the object’s method, and finally the aggregate will be saved.

Raises:

  • (ArgumentError)


18
19
20
21
22
# File 'lib/akasha/command_router.rb', line 18

def register(command, aggregate_class = nil, &block)
  raise ArgumentError, 'Pass either aggregate class or block' if aggregate_class && block
  handler = aggregate_class || block
  @routes[command] = handler
end

#route!(command, aggregate_id, options = {}, **data) ⇒ Object

Routes a command to the registered target. Raises ‘NotFoundError` if no corresponding target can be found.

Arguments:

- command - name of the command
- aggregate_id - aggregate id
- options - flags:
  - transactor - transactor instance to replace the default one (`OptimisticTransactor`);
See docs for `OptimisticTransactor` for a list of additional supported options.


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/akasha/command_router.rb', line 33

def route!(command, aggregate_id, options = {}, **data)
  handler = @routes[command]
  case handler
  when Class
    transactor = options.fetch(:transactor, default_transactor)
    transactor.call(handler, command, aggregate_id, options, **data)
  when handler.respond_to?(:call)
    handler.call(command, aggregate_id, options, **data)
  when Proc
    handler.call(command, aggregate_id, options, **data)
  when nil
    raise HandlerNotFoundError, "Handler for command #{command.inspect} not found"
  else
    raise UnsupportedHandlerError, "Unsupported command handler #{handler.inspect}"
  end
end