Add the EnrichCommand
middleware to your command router:
defmodule MyApp.Router do
use Commanded.Commands.Router
middleware Middleware.EnrichCommand
end
Implement the CommandEnrichment
protocol for any command which needs external data, such as an external API or read model query.
defimpl CommandEnrichment, for: ExampleCommand do
@doc """
Enrich command during dispatch, but before aggregate handling.
"""
def enrich(%ExampleCommand{} = command) do
%ExampleCommand{id: id} = command
command = %ExampleCommand{
command
| external_data: lookup_external_data(id)
}
{:ok, command}
end
defp lookup_external_data(id) do
# .. fetch data
end
end
The enrich/1
function should return {:ok, command}
on success, or {:error, error}
on failure.