Commanded v0.13.0 Commanded.Commands.Router View Source

Command routing macro to allow configuration of each command to its command handler.

Example

defmodule BankRouter do
  use Commanded.Commands.Router

  dispatch OpenAccount, to: OpenAccountHandler, aggregate: BankAccount, identity: :account_number
end

:ok = BankRouter.dispatch(%OpenAccount{account_number: "ACC123", initial_balance: 1_000})

The command handler module must implement a handle/2 function that receives the aggregate’s state and the command to execute. It should delegate the command to the aggregate.

Dispatch command directly to an aggregate root

You can route a command directly to an aggregate root, without requiring an intermediate command handler.

Example

defmodule BankRouter do
  use Commanded.Commands.Router

  dispatch OpenAccount, to: BankAccount, identity: :account_number
end

The aggregate root must implement an execute/2 function that receives the aggregate’s state and the command being executed.

Aggregate version

You can optionally choose to include the aggregate’s version as part of the dispatch result by setting include_aggregate_version true.

{:ok, aggregate_version} = BankRouter.dispatch(command, include_aggregate_version: true)

This is useful when you need to wait for an event handler (e.g. a read model projection) to be up-to-date before continuing or querying its data.

Link to this section Summary

Functions

Configure the command, or list of commands, to be dispatched to the corresponding handler for a given aggregate root

Include the given middleware module to be called before and after success or failure of each command dispatch

Link to this section Functions

Link to this macro dispatch(command_module_or_modules, opts) View Source (macro)

Configure the command, or list of commands, to be dispatched to the corresponding handler for a given aggregate root

Link to this macro middleware(middleware_module) View Source (macro)

Include the given middleware module to be called before and after success or failure of each command dispatch

The middleware module must implement the Commanded.Middleware behaviour.

Middleware modules are executed in the order they are defined.

Example

defmodule BankingRouter do
  use Commanded.Commands.Router

  middleware CommandLogger
  middleware MyCommandValidator
  middleware AuthorizeCommand

  dispatch [OpenAccount,DepositMoney] to: BankAccount, identity: :account_number
end