Cqrs.Query behaviour (cqrs_tools v0.1.7) View Source

Defines a query and any filters.

Options

  • require_all_filters - If true, all filters will be required. Defaults to false

Examples

defmodule GetUser do
  use Cqrs.Query
  alias Cqrs.QueryTest.User

  filter :email, :string, required: true

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

  @impl true
  def handle_create([email: email], _opts) do
    from u in User, where: u.email == ^email
  end

  @impl true
  def handle_execute(query, opts) do
    {:ok, Repo.all(query, opts)}
  end
end

Creation

iex> GetUser.new!()
** (Cqrs.Query.QueryError) %{email: ["can't be blank"]}

iex> GetUser.new!(email: "wrong")
** (Cqrs.Query.QueryError) %{email: ["has invalid format"]}

iex> {:error, %{errors: errors}} = GetUser.new()
...> errors
[email: {"can't be blank", [validation: :required]}]

iex> {:error, %{errors: errors}} = GetUser.new(email: "wrong")
...> errors
[email: {"has invalid format", [validation: :format]}]

iex> {:ok, query} = GetUser.new(email: "chris@example.com")
...> query
#Ecto.Query<from u0 in User, where: u0.email == ^"chris@example.com">

Execution

iex> {:ok, user} =
...> GetUser.new(email: "chris@example.com")
...> |> GetUser.execute()
...> %{id: user.id, email: user.email}
%{id: "052c1984-74c9-522f-858f-f04f1d4cc786", email: "chris@example.com"}

Link to this section Summary

Link to this section Types

Link to this section Functions

Link to this function

execute(mod, query, opts)

View Source
Link to this macro

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

View Source (macro)

Defines a Query filter.

  • :name - any atom

  • :type - any valid Ecto Schema type

  • :opts - any valid Ecto Schema field options. Plus:

    • :required - true | false. Defaults to the require_all_filters option.
    • :description - Documentation for the field.

Link to this section Callbacks

Link to this callback

handle_create(filters, opts)

View Source

Specs

handle_create(filters(), opts()) :: query()
Link to this callback

handle_execute(arg1, opts)

View Source

Specs

handle_execute(Ecto.Query.t(), opts()) ::
  {:ok, any()} | {:error, query()} | {:error, any()}
Link to this callback

handle_validate(arg1, opts)

View Source

Specs

handle_validate(Ecto.Changeset.t(), opts()) :: Ecto.Changeset.t()