빠른 참조

Absinthe GraphQL 치트시트

Elixir 및 Phoenix 프레임워크를 위한 GraphQL 구현체 Absinthe 빠른 가이드: 스키마, 리졸버, 커스텀 타입, 쿼리 및 뮤테이션.

· 게시일

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

관련 참조 문서

관련 주제