Absinthe は、ElixirおよびPhoenixアプリケーション向けの高機能なGraphQLツールキットです。
コアコンセプト(Core Concepts)
- Schema: クエリ、ミューテーション、型定義のルート定義。
- Resolver: データの取得または更新を行うElixir関数。
- Type: 返却されるデータエンティティの構造とフィールド定義。
PhoenixでのPlug統合
# 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