EctoCommand (EctoCommand v0.2.7)

View Source

The EctoCommand module provides a DSL for defining command schemas. It is used by use EctoCommand in your command modules.

Example

defmodule MyApp.Commands.CreatePost do
  use EctoCommand
  alias MyApp.PostRepository

  command do
    param :title, :string, required: true, length: [min: 3, max: 255]
    param :body, :string, required: true, length: [min: 3]

    internal :slug, :string
    internal :author, :string
  end

  def execute(%__MODULE__{} = command) do
    ...
    :ok
  end

  def fill(:slug, _changeset, %{"title" => title}, _metadata) do
    Slug.slufigy(title)
  end

  def fill(:author, _changeset, _params, %{"triggered_by" => triggered_by}) do
    triggered_by
  end

  def fill(:author, changeset, _params, _metadata) do
    Ecto.Changeset.add_error(changeset, :triggered_by, "triggered_by metadata info is missing")
  end
end

Summary

Functions

The command/1 macro defines a command schema with the given block.

Defines a command internal field.

Defines a command parameter field.

Functions

cast_embedded_fields(changeset, embedded_fields)

command(list)

(macro)

The command/1 macro defines a command schema with the given block.

Examples

 command do
   param :name, :string
   param :age, :integer
 end

embeds_one(name, schema, list)

(macro)

internal(name, type \\ :string, opts \\ [])

(macro)

Defines a command internal field.

These fields will be ignored during the "cast process". Instead, you need to define a public fill/4 function to populate them. The fill/4 function takes four arguments: the name of the field, the current temporary changeset, the parameters received from external sources, and additional metadata. You can choose to return the value that will populate the field or the updated changeset. Both options are acceptable, but returning the changeset is particularly useful if you want to add errors to it.

Examples

 internal :slug, :string
 internal :author, :string

param(name, type, opts \\ [])

(macro)

Defines a command parameter field.

The param macro is based on the field macro of Ecto.Schema and defines a field in the schema with a given name and type. You can pass all the options supported by the field macro. Afterwards, each defined param is cast with the "external" data received. In addition to those options, the param macro accepts a set of other options that indicate how external data for that field should be validated. These options are applied to the intermediate Changeset created in order to validate data. These options are mapped into validate_* methods of the Ecto.Changeset.

Examples

param :title, :string, required: true, length: [min: 3, max: 255]
param :body, :string, required: true, length: [min: 3]

validate_with(function, opts \\ [])

(macro)