Краткий справочник

Шпаргалка по Absinthe GraphQL

Справочное руководство по Absinthe GraphQL в Elixir и Phoenix: схемы, резолверы, типы, запросы и мутации.

· Опубликовано

Absinthe — полнофункциональный инструментарий GraphQL для приложений на Elixir и Phoenix.

Ключевые понятия (Core Concepts)

  • Schema: Корневое определение запросов, мутаций и типов.
  • Resolver: Функция Elixir, отвечающая за получение или изменение данных.
  • Type: Описывает структуру и поля возвращаемых сущностей.

Интеграция Plug в Phoenix

# web/router.ex
defmodule Blog.Web.Router do
  use Phoenix.Router

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

Absinthe работает как Plug, принимая конфигурацию корневой схемы.


Определение схемы (Schema Definition)

# web/schema.ex
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

Обрабатывает { posts { ... } } и делегирует выполнение функции-резолверу.

Резолверы (Resolvers)

# web/resolvers/post_resolver.ex
defmodule Blog.PostResolver do
  def all(_args, _info) do
    {:ok, Blog.Repo.all(Blog.Post)}
  end
end

Резолверы возвращают {:ok, result} или {:error, reason}.

Пользовательские типы (Custom Types)

# web/schema/types.ex
defmodule Blog.Schema.Types do
  use Absinthe.Schema.Notation

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

Запросы и мутации (Queries & Mutations)

Аргументы запроса

{
  user(id: "1") {
    name
    email
  }
}
# web/schema.ex
query do
  field :user, type: :user do
    arg :id, non_null(:id)
    resolve &Blog.UserResolver.find/2
  end
end
def find(%{id: id} = _args, _info) do
  case Blog.Accounts.get_user(id) do
    nil -> {:error, "User not found"}
    user -> {:ok, user}
  end
end

Мутации (Mutations)

mutation CreatePost {
  post(title: "Hello World") {
    id
    title
  }
}
# web/schema.ex
mutation do
  @desc "Create a new post"
  field :post, type: :post do
    arg :title, non_null(:string)
    resolve &Blog.PostResolver.create/2
  end
end

Связанные руководства

Связанные темы