View Source Trolleybus.Event (trolleybus v0.3.0)
Defines an event struct for publishing via Trolleybus
.
An event definition is composed of a couple of elements:
handler/1
declarations - they define which handlers are called when event is published.message/1
declaration - determines the underlying struct and types of fields usingfield/3
validated before publishing.
example
Example
defmodule App.Events.EmailInvitedToDocument do
use Trolleybus.Event
handler(App.Handlers.EmailHandler)
handler(App.Handlers.StripeHandler)
message do
field(:invitee_email, App.Types.Email)
field(:document, %Document{})
field(:inviter, %User{})
field(:message, :string, required: false)
field(:vat_invoice?, :boolean, default: false)
end
end
Event can declare any number of handlers, including zero. Message shape
is declared by a series of field/3
macro calls. Each field/3
declaration
maps to a field in the underlying, generated struct.
Events can be instantiated like any other struct:
iex> event = %App.Events.EmailInvitedToDocument{
invitee_email: "alice@example.com",
document: document,
inviter: user
}
Each event implements cast!/1
function which is called before publishing
it. This function returns the same event struct with casted and validated
message parameters as well as declared handlers.
Link to this section Summary
Functions
Defines a field on the event with a given name and type.
Indicates a handler the event is dispatched to.
Defines an event struct.
Link to this section Functions
Defines a field on the event with a given name and type.
All field definitions must be put inside message/1
block.
The macro accepts three arguments:
name
- name of the field in the underlying struct.type
- declares the expected type of the field value. It's validated iternally viacast!/1
.opts
- additional options for the field. Currently,required
anddefault
are accepted.
options
Options
:required
- boolean determining whether field value can be left empty (nil
). If field'srequired
option is set totrue
and event is instantiated and casted with that field left empty, an error is raised. Defaults to:true
.:default
- sets field value to the provided default when field is left empty during instantiating the event. Defaults to:nil
.
field-types
Field types
The underlying validation logic uses Ecto.Changeset
, so basically any type
accepted by Ecto.Schema
is also accepted in message field definition.
There's a special case for passing structs - %StructModule{}
. This is
because we don't want to validate exact contents of the struct, only that
the value passed is a struct and is of matching type.
Indicates a handler the event is dispatched to.
The macro accepts a module name. That name is later validated when
casting the event internally via cast!/1
. If the handler does not
implement theTrolleybus.Handler
behaviour or does not explicitly
handle that particular event, an error is raised.
Defines an event struct.
Each struct field is defined using field/3
macro.