Home

Awesome

Crudry

Coverage Status

Crudry is an elixir library for DRYing CRUD of Phoenix Contexts and Absinthe Resolvers.

It also provides a simple middleware for translating changeset errors into readable messages.

Documentation can be found at https://hexdocs.pm/crudry.

The changelog can be found at the Releases page.

Installation

The package can be installed by adding crudry to your list of dependencies in mix.exs:

def deps do
  [
    {:crudry, "~> 2.4.0"},
  ]
end

Usage

Context Generation

To generate CRUD functions for a given schema in your context, simply do:

defmodule MyApp.MyContext do
  alias MyApp.Repo

  require Crudry.Context
  Crudry.Context.generate_functions MyApp.MySchema
end

To see the functions that are generated and custom options, refer to the Crudry.Context docs.

Resolver Generation

With the context all set up, the resolver is ready to be generated:

defmodule MyApp.MyResolver do
  alias MyApp.Repo

  require Crudry.Resolver
  Crudry.Resolver.generate_functions MyApp.MyContext, MyApp.MySchema
end

To see the functions that are generated and custom options, refer to the Crudry.Resolver docs.

Translate Errors middleware

Absinthe Middleware to translate errors and changeset errors into human readable messages. It support nested changeset errors and internationalization, using Gettext.

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

alias Crudry.Middlewares.TranslateErrors

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

  resolve &UsersResolver.create_user/2
  middleware TranslateErrors
end

To handle errors for all fields, use middleware/3:

alias Crudry.Middlewares.TranslateErrors

def middleware(middleware, _field, _object) do
  middleware ++ [TranslateErrors]
end

Crudry.Translator is used by default to translate error messages to the default locale en. You can also use your own Gettext module by adding it to your Absinthe's schema context/1 function:

def context(context) do
  Map.put(context, :translator, MyAppWeb.Gettext)
end

Or just override the default locale in your Context Plug:

def call(conn, _) do
  Absinthe.Plug.put_options(conn, context: %{locale: "pt_BR"})
end

Refer to the TranslateErrors docs for more information.

Related Projects

License

MIT License.

See LICENSE for more information.