Cqrs.Query behaviour (cqrs_tools v0.5.28) View Source
Defines a query and any filters.
Options
require_all_filters
- Iftrue
, all filters will be required. Defaults tofalse
Examples
defmodule GetUser do
use Cqrs.Query
alias Cqrs.QueryTest.User
filter :email, :string, required: true
binding :user, User
option :exists?, :boolean,
default: false,
description: "If `true`, only check if the user exists."
@impl true
def handle_validate(filters, _opts) do
Changeset.validate_format(filters, :email, ~r/@/)
end
@impl true
def handle_create([email: email], _opts) do
from u in User, as: :user, where: u.email == ^email
end
@impl true
def handle_execute(query, opts) do
case Keyword.get(opts, :exists?) do
true -> Repo.exists?(query, opts)
false -> Repo.one(query, opts)
end
end
end
Creation
iex> GetUser.new!()
** (Cqrs.QueryError) email can't be blank
iex> GetUser.new!(email: "wrong")
** (Cqrs.QueryError) email has invalid format
iex> {:error, errors} = GetUser.new()
...> errors
%{email: ["can't be blank"]}
iex> {:error, errors} = GetUser.new(email: "wrong")
...> errors
%{email: ["has invalid 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
Defines a Query filter.
:name
- anyatom
:type
- any valid Ecto Schema type:opts
- any valid Ecto Schema field options. Plus::required
-true | false
. Defaults to therequire_all_filters
option.:description
- Documentation for the field.
Specs
Describes a supported option for this query.
Options
:default
- this default value if the option is not provided.:description
- The documentation for this option.