Chronicle.Events.EventType behaviour (cratis_chronicle v1.0.2)

Copy Markdown View Source

Macro for defining Chronicle event types.

Use Chronicle.Events.EventType in an event struct module to annotate it with a stable event type identifier and generation number. Chronicle uses these to register the event schema and route events to the correct observers.

You can also declare model-bound constraints directly on the event type through attributes:

defmodule MyApp.Events.UserRegistered do
  use Chronicle.Events.EventType, id: "user-registered-v1"
  defstruct [:email]

  @unique :email
  unique_event_type()
end

defmodule MyApp.Events.UserDeleted do
  use Chronicle.Events.EventType, id: "user-deleted-v1"
  defstruct [:email]

  @remove_constraint "email"
end

Usage

defmodule MyApp.Events.AccountOpened do
  use Chronicle.Events.EventType, id: "account-opened-v1"
  defstruct [:account_id, :owner_name, :initial_balance]
end

With an explicit generation:

defmodule MyApp.Events.FundsDeposited do
  use Chronicle.Events.EventType, id: "funds-deposited", generation: 2
  defstruct [:account_id, :amount, :currency]
end

Introspection

Modules that use Chronicle.Events.EventType expose metadata via __chronicle_event_type__/1:

MyApp.Events.AccountOpened.__chronicle_event_type__(:id)
#=> "account-opened-v1"

MyApp.Events.AccountOpened.__chronicle_event_type__(:generation)
#=> 1

Chronicle also generates a Jason.Encoder implementation automatically so events can be serialized to JSON for storage. Event fields are encoded using their atom keys as-is (snake_case).

Summary

Callbacks

Returns metadata for this event type module.

Functions

Declares that appending this event removes a named constraint.

Declares a unique constraint for one or more event fields.

Declares a unique constraint for the whole event type.

Callbacks

__chronicle_event_type__(key)

@callback __chronicle_event_type__(key :: :id | :generation | :constraints | :pii) ::
  term()

Returns metadata for this event type module.

Accepts :id, :generation, or :constraints as the key.

Functions

remove_constraint(name)

(macro)

Declares that appending this event removes a named constraint.

This is equivalent to setting @remove_constraint.

unique(fields, opts \\ [])

(macro)

Declares a unique constraint for one or more event fields.

This is equivalent to setting @unique.

unique_event_type(opts \\ [])

(macro)

Declares a unique constraint for the whole event type.

This is equivalent to setting @unique_event_type.