Cqrs.CommandValidation (cqrs_tools v0.1.7) View Source

Defines validation functions for a validated command.

Example

defmodule CreateUser do
  use Cqrs.Command
  alias Cqrs.CommandValidation

  field :email, :string
  field :name, :string
  field :id, :binary_id, internal: true

  derive_event UserCreated

  @impl true
  def handle_validate(command, _opts) do
    Ecto.Changeset.validate_format(command, :email, ~r/@/)
  end

  @impl true
  def after_validate(%{email: email} = command) do
    Map.put(command, :id, UUID.uuid5(:oid, email))
  end

  @impl true
  def before_dispatch(command, _opts) do
    command
    |> CommandValidation.new()
    |> CommandValidation.add(&ensure_uniqueness/1)
    |> CommandValidation.run()
  end

  @impl true
  def handle_dispatch(_command, _opts) do
    {:ok, :dispatched}
  end

  defp ensure_uniqueness(%{id: id}) do
    if Repo.exists?(from u in User, where: u.id == ^id),
      do: {:error, "user already exists"},
      else: :ok
  end
end

Link to this section Summary

Functions

Adds a validation_function to the list of validations to run.

Creates a new Cqrs.CommandValidation struct.

Runs the list of 'validation_function' functions

Link to this section Types

Specs

command() :: map()

Specs

t() :: %Cqrs.CommandValidation{command: command(), validations: list()}

Specs

validation_function() ::
  (command() -> any() | {:error, any()})
  | (command(), keyword() -> any() | {:error, any()})

Link to this section Functions

Specs

add(t(), validation_function()) :: t()

Adds a validation_function to the list of validations to run.

Specs

new(command()) :: t()

Creates a new Cqrs.CommandValidation struct.

Link to this function

run(validation, opts \\ [])

View Source

Specs

run(t(), keyword()) :: {:ok, command()} | {:error, list()}

Runs the list of 'validation_function' functions