Crudry v1.2.3 Crudry.Middlewares.HandleChangesetErrors View Source

Absinthe Middleware to translate changeset errors into human readable messages. It supports nested errors.

Usage

To handle errors for a field, add it after the resolve, using middleware/2:

alias Crudry.Middlewares.HandleChangesetErrors

field :create_user, :user do
  arg :params, non_null(:user_params)

  resolve &UsersResolver.create_user/2
  middleware HandleChangesetErrors
end

To handle errors for all fields, use Object Wide Authentication:

alias Crudry.Middlewares.HandleChangesetErrors

# Only add the middleware to mutations
def middleware(middleware, _field, %Absinthe.Type.Object{identifier: identifier})
when identifier in [:mutation] do
  middleware ++ [HandleChangesetErrors]
end

def middleware(middleware, _field, _object) do
  middleware
end

Examples

For a simple changeset error:

#Ecto.Changeset<
  action: nil,
  changes: %{},
  errors: [username: {"can't be blank", [validation: :required]}],
  data: #Crudry.User<>,
  valid?: false
>

The resulting error will be ["username can't be blank"]

For a changeset with nested errors:

#Ecto.Changeset<
  action: nil,
  changes: %{
    posts: [
      #Ecto.Changeset<
        action: :insert,
        changes: %{},
        errors: [
          title: {"can't be blank", [validation: :required]},
          user_id: {"can't be blank", [validation: :required]}
        ],
        data: #Crudry.Post<>,
        valid?: false
      >
    ]
  },
  errors: [
    username: {"should be at least %{count} character(s)",
    [count: 2, validation: :length, kind: :min]}
  ],
  data: #Crudry.User<>,
  valid?: false
>

The resulting error will be ["posts: title can't be blank", "posts: user_id can't be blank", "username should be at least 2 character(s)"]

Link to this section Summary

Functions

This is the main middleware callback

Link to this section Functions

Link to this function

call(resolution, config) View Source

This is the main middleware callback.

It receives an %Absinthe.Resolution{} struct and it needs to return an %Absinthe.Resolution{} struct. The second argument will be whatever value was passed to the middleware call that setup the middleware.

Callback implementation for Absinthe.Middleware.call/2.