Freight is a library for Absinthe GraphQL that helps you build mutation payload results. Inspired by the GraphQL APIs of GitHub and Shopify, who also aim to keep syntactical GraphQL errors, like missing fields and malformed queries, seperate from validation and other business logic errors.
It is heavily inspired by Kronky, I decided to build my own library because I did not like how much it is focussed on ecto changesets, and missed customisability that was required for a project I work on.
You can set a custom error object that will be returned in the errors array in your payloads. This object must be defined in the schema you're calling define_payload
from.
config :freight,
error_object: :user_error
# whenever a field is snake-cased (like an ecto field for example), setting this to `true` will camelize it like Absinthe would
lower_camelize_field_name: true
Below is a documented example of how to define Freight payloads in your schema
defmodule FreightDemo.Schema.Example do
use Absinthe.Schema.Notation
import Freight.Payload
object :user do
field(:name, :string)
end
object :comment do
field(:body, :string)
field(:author, :user)
end
define_payload(:create_comment_payload, author: :user, comment: :comment)
field :create_comment, type: :create_comment_payload do
arg(:body, non_null(:string))
resolve(&FreightDemo.Resolver.create_comment/3)
middleware(&build_payload/2)
end
end
Returning errors works just like in Absinthe
defmodule FreightDemo.Resolver do
def create_comment(_parent, %{body: body}, _context) do
# your logic
{:ok, author: %{}, comment: %{}}
end
# OR
def create_comment(_parent, %{body: body}, _context) do
# your logic
{:error, "Something went horribly wrong!"}
end
end
More extensive documentation on defining errors can be found in the documentation
Add the following to your mix.exs file
def deps do
[
{:freight, "~> 0.4.0"}
]
end
Documentation can be found at https://hexdocs.pm/freight.