View Source Trolleybus.Handler behaviour (trolleybus v0.2.0)

Defines a handler for events published via Trolleybus

An event handler is expected to implement handle_event/1 callback.

example

Example

defmodule App.Handlers.StripeHandler do
  use Trolleybus.Handler

  def handle_event(%EmailInvitedToDocument{email: email} = event) do
    ...
  end

  def handle_event(%UserInvitedToDocument{user: user, document: document) do
    ...
  end
end

defining-event-handlers

Defining event handlers

The shape of the function head for the callback is expected to meet certain criteria. Each implemented clause must have one of the following shapes:

def handle_event(%EventModule{...}) do
  ...
end

or:

def handle_event(%EventModule{...} = event) do
  ...
end

Matching on the contents of the event is in turn restricted to binding keys to variables only, which means that this clause is accepted:

def handle_event(%EventModule{field: value}) do
  ...
end

while this clause will raise an error:

def handle_event(%EventModule{field: %{} = value) do
  ...
end

Any other pattern in any of the clauses is going to result in raising an error. This restriction allows to implicitly infer a list of events supported by the handler, which is later used when validating handlers declared for the published event in Trolleybus.Event. This also enforces consistent pattern matching on exact events across all implemented handlers and guarantees exhaustive matching.

Link to this section Summary

Callbacks

Defines event handler for handled events.

Link to this section Callbacks

@callback handle_event(struct()) :: term()

Defines event handler for handled events.

Each supported event is expected to be handled by a distinct function clause using pattern matching. For more information on expected implementation of the callback, see "Defining event handlers" above.