Γρήγορη αναφορά

Φύλλο οδηγιών Absinthe GraphQL

Γρήγορος οδηγός αναφοράς για το Absinthe GraphQL στην Elixir και το Phoenix: σχήματα, resolvers, τύποι και mutations.

· Δημοσιεύτηκε

Το 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.


Ορισμός Schema (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 { ... } } και αναθέτει στον resolver.

Resolvers

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

Οι resolvers επιστρέφουν {: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

Σχετικές αναφορές

Σχετικά θέματα