Class: NexusCqrs::CommandBus
- Inherits:
-
Object
- Object
- NexusCqrs::CommandBus
- 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.
Constant Summary collapse
- UnregisteredHandler =
Class.new(StandardError)
- MultipleHandlers =
Class.new(StandardError)
Instance Attribute Summary collapse
- #handlers ⇒ Object readonly
Instance Method Summary collapse
-
#call(message) ⇒ Object
Invokes a handler from a message.
-
#clear_handlers ⇒ Object
Removes all registered handlers from the bus.
-
#initialize(middleware: nil) ⇒ CommandBus
constructor
A new instance of CommandBus.
-
#register(message, handler) ⇒ Object
Registers a handler for a command.
-
#registered_handlers ⇒ ThreadSafe::Cache
Return a list of registered handlers.
Constructor Details
#initialize(middleware: nil) ⇒ CommandBus
Returns a new instance of CommandBus.
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
#handlers ⇒ Object (readonly)
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
38 39 40 41 42 43 |
# File 'lib/nexus_cqrs/command_bus.rb', line 38 def call() runner = Middleware::Builder.new runner.use(@middleware) runner.use(->() { handler_for_command().call() }) runner.call() end |
#clear_handlers ⇒ Object
Removes all registered handlers from the bus. This can be useful in tests - as we don’t want state to persist across handlers
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.
27 28 29 30 31 |
# File 'lib/nexus_cqrs/command_bus.rb', line 27 def register(, handler) raise MultipleHandlers, "Multiple handlers not allowed for #{}" if handlers[] handlers[] = handler end |
#registered_handlers ⇒ ThreadSafe::Cache
Return a list of registered handlers
50 51 52 |
# File 'lib/nexus_cqrs/command_bus.rb', line 50 def registered_handlers handlers end |