Class: NexusCqrs::CommandBus

Inherits:
Object
  • Object
show all
Defined in:
lib/nexus_cqrs/command_bus.rb

Overview

The command bus is responsible for registering and invoking the handlers. It stores a simple list of all registered commands, along with their handlers. When a message is passed to ‘call`, the middleware is triggered for the message then the handler is invoked.

Since:

  • 0.1.0

Constant Summary collapse

UnregisteredHandler =

Since:

  • 0.1.0

Class.new(StandardError)
MultipleHandlers =

Since:

  • 0.1.0

Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(middleware: nil) ⇒ CommandBus

Returns a new instance of CommandBus.

Since:

  • 0.1.0



15
16
17
18
# File 'lib/nexus_cqrs/command_bus.rb', line 15

def initialize(middleware: nil)
  @handlers = ThreadSafe::Cache.new
  @middleware = middleware || Middleware::Builder.new
end

Instance Attribute Details

#handlersObject (readonly)

Since:

  • 0.1.0



62
63
64
# File 'lib/nexus_cqrs/command_bus.rb', line 62

def handlers
  @handlers
end

Instance Method Details

#call(message) ⇒ Object

Invokes a handler from a message

Parameters:

Since:

  • 0.1.0



38
39
40
41
42
43
# File 'lib/nexus_cqrs/command_bus.rb', line 38

def call(message)
  runner = Middleware::Builder.new
  runner.use(@middleware)
  runner.use(->(message_) { handler_for_command(message_).call(message_) })
  runner.call(message)
end

#clear_handlersObject

Removes all registered handlers from the bus. This can be useful in tests - as we don’t want state to persist across handlers

Since:

  • 0.1.0



58
59
60
# File 'lib/nexus_cqrs/command_bus.rb', line 58

def clear_handlers
  @handlers = ThreadSafe::Cache.new
end

#register(message, handler) ⇒ Object

Registers a handler for a command.

Parameters:

Raises:

  • (MultipleHandlers)

    If the message already has a handler registered, an error will be raised

Since:

  • 0.1.0



27
28
29
30
31
# File 'lib/nexus_cqrs/command_bus.rb', line 27

def register(message, handler)
  raise MultipleHandlers, "Multiple handlers not allowed for #{message}" if handlers[message]

  handlers[message] = handler
end

#registered_handlersThreadSafe::Cache

Return a list of registered handlers

Returns:

  • (ThreadSafe::Cache)

    ThreadSafe::Cache object containing a list of all the registered handlers

Since:

  • 0.1.0



50
51
52
# File 'lib/nexus_cqrs/command_bus.rb', line 50

def registered_handlers
  handlers
end