Absinthe Cheat Sheet

From WikiOD

Here is the cheatsheat of Absinthe and basic guide on how to use Absinthe

Introduction[edit | edit source]

Concepts[edit | edit source]

  • Schema - The root. Defines what queries you can do, and what types they return.
  • Resolver - Functions that return data.
  • Type - A type definition describing the shape of the data you’ll return.

Plug[edit | edit source]

web/router.ex[edit | edit source]

defmodule Blog.Web.Router do
  use Phoenix.Router

  forward "/", Absinthe.Plug,
    schema: Blog.Schema
end

{: data-line=“4,5”}

Absinthe is a Plug, and you pass it one Schema.

See: Our first query

Main concepts[edit | edit source]

{: .-three-column}

Schema[edit | edit source]

web/schema.ex[edit | edit source]

defmodule Blog.Schema do
  use Absinthe.Schema
  import_types Blog.Schema.Types

  query do
    @desc "Get a list of blog posts"
    field :posts, list_of(:post) do
      resolve &Blog.PostResolver.all/2
    end
  end
end

{: data-line=“5,6,7,8,9,10”}

This schema will account for { posts { ··· } }. It returns a Type of :post, and delegates to a Resolver.

Resolver[edit | edit source]

web/resolvers/post_resolver.ex[edit | edit source]

defmodule Blog.PostResolver do
  def all(_args, _info) do
    {:ok, Blog.Repo.all(Blog.Post)}
  end
end

{: data-line=“3”}

This is the function that the schema delegated the posts query to.

Type[edit | edit source]

web/schema/types.ex[edit | edit source]

defmodule Blog.Schema.Types do
  use Absinthe.Schema.Notation

  @desc "A blog post"
  object :post do
    field :id, :id
    field :title, :string
    field :body, :string
  end
end

{: data-line=“4,5,6,7,8,9”}

This defines a type :post, which is used by the resolver.

Schema[edit | edit source]

Query arguments[edit | edit source]

GraphQL query[edit | edit source]

{ user(id: "1") { ··· } }

web/schema.ex[edit | edit source]

query do
  field :user, type: :user do
    arg :id, non_null(:id)
    resolve &Blog.UserResolver.find/2
  end
end

{: data-line=“3”}

Resolver[edit | edit source]

def find(%{id: id} = args, _info) do
  ···
end

{: data-line=“1”}

See: Query arguments

Mutations[edit | edit source]

GraphQL query[edit | edit source]

{
  mutation CreatePost {
    post(title: "Hello") { id }
  }
}

web/schema.ex[edit | edit source]

mutation do
  @desc "Create a post"
  field :post, type: :post do
    arg :title, non_null(:string)
    resolve &Blog.PostResolver.create/2
  end
end

{: data-line=“1”}

See: Mutations

References[edit | edit source]

  • Absinthe website (absinthe-graphql.org)
  • [[./graphql|GraphQL cheatsheet]] (devhints.io)

Credit:rstacruz