はのちゃ爆発

はのちゃが技術ネタとか日常のこととかを書いてます。

graphql-ruby をさくっと使うメモ

自分用備忘録。

graphql-ruby を入れる

とりあえずインストール。 gem 'graphql' を Gemfile に書いて $ bundle install

graphql-ruby の初期化

以下のコマンドでセットアップ。

$ bin/rails g graphql:install

実行後再度 $ bundle install する。

Query を作ってみる

モデル類は適当に作ってある前提。

$ bin/rails g graphql:object Hoge some_field:String

app/graphql/types 以下に新しいオブジェクトが生成される。

module Types
  class HogeType < Types::BaseObject
    field :some_field, String, null: true
  end
end

オブジェクトができたので Query を追加する。

field :hoge, HogeType, null: true do
  description "Find a hoge by ID"
  argument :id, Int, required: true
end

def hoge(id:)
  # ここに hoge のリゾルバを定義
  Hoge.find(id)
end

field 定義時、 argument の引数である reqiured は必須パラメータっぽい(何も書かないとエラーになった)。

field の第一引数として渡しているシンボルと同じ名前のメソッドがリゾルバになるっぽい?

上記は #show とかに相当する Query になる。 #index に相当するものだと以下のようになる?

field :hoges, [HogeType], null: true do
  description "Get all hoges"
end

def hoges
  Hoge.all
end

本来は hoge で複数の結果を返せるようにするべきか、あるいは検索は別フィールドにすべきか。作法を調べたほうがよさそう。

Mutation を追加する

ここまでは Getting Started 通りにやれば分かるのでいいが、 Mutation は似たようなガイドが見当たらなかったのでちょっと苦労した。

UpdateHoge 的な Mutation のを追加、 Create が出来る部分までやる。

Generator で Mutation の雛形を作る

Mutation を作るジェネレータがあるのでそれを使う。

$ bin/rails g graphql:mutation CreateHoge

app/graphql/mutations 以下に create_hoge.rb 的なものができる。

module Mutations
  class CreateDepo < GraphQL::Schema::RelayClassicMutation
    # 作成後に返す結果を field で定義
    # エラーもちゃんと返す場合はここでエラー用フィールドを定義する
    field :hoge, Types::HogeType, null: false

    # 作成時に渡す引数
    # Hoge の作成に必要な情報を渡す
    argument :some_field, String, required: true

    # 実際の作成処理を記述する
    # 返り値は上で記述した field をキーに持つオブジェクト
    # 失敗した時はそれに対応したエラーを返すように設計する必要がある
    def resolve(some_field:)
      hoge = Hoge.create(some_field: some_field)
      return { hoge: hoge }
    end
  end
end

ジェネレータ実行時に app/graphql/types/mutation_type.rb が編集され、上記で編集した Mutation が使えるように設定されているはず。

module Types
  class MutationType < Types::BaseObject
    field :createHoge, mutation: Mutations::CreateHoge
  end
end