Commanded v0.13.0 Commanded.Event.Handler behaviour View Source

Defines the behaviour an event handler must implement.

Provides a convenience macro that implements the behaviour, allowing you to handle only the events you are interested in processing.

You should start your event handlers using a Supervisor to ensure they are restarted on error.

Event handler name

The name you specify is used when subscribing to the event store. Therefore you should not change the name once the handler has been deployed. A new subscription will be created when you change the name, and you event handler will receive already handled events.

Subscription options

You can choose to start the event handler’s event store subscription from :origin, :current position, or an exact event number using the start_from option. The default is to use the origin so your handler will receive all events.

Use the :current position when you don’t want newly created event handlers to go through all previous events. An example would be adding an event handler to send transactional emails to an already deployed system containing many historical events.

Example

Set the start_from option (:origin, :current, or an explicit event number) when using Commanded.Event.Handler:

defmodule AccountBalanceHandler do
  use Commanded.Event.Handler, name: "AccountBalanceHandler", start_from: :origin

  # ...
end

You can optionally override :start_from by passing it as option when starting your handler:

{:ok, _handler} = AccountBalanceHandler.start_link(start_from: :current)

Link to this section Summary

Functions

Macro as a convenience for defining an event handler

Callbacks

Event handler behaviour to handle a domain event and its metadata

Link to this section Types

Link to this type domain_event() View Source
domain_event() :: struct
Link to this type metadata() View Source
metadata() :: struct
Link to this type subscribe_from() View Source
subscribe_from() :: :origin | :current | non_neg_integer

Link to this section Functions

Link to this macro __using__(opts) View Source (macro)

Macro as a convenience for defining an event handler

Example

defmodule ExampleHandler do

use Commanded.Event.Handler, name: "ExampleHandler"

def handle(%AnEvent{...}, _metadata) do
  # ...
end

end

Start event handler process (or configure as a worker inside a supervisor):

{:ok, handler} = ExampleHandler.start_link()

Link to this function start_link(handler_name, handler_module, opts \\ []) View Source

Link to this section Callbacks

Link to this callback handle(domain_event, metadata) View Source
handle(domain_event, metadata) :: :ok | {:error, reason :: atom}

Event handler behaviour to handle a domain event and its metadata

Return :ok on success, {:error, :already_seen_event} to ack and skip the event, or {:error, reason} on failure.