LoginSignup
4
5

More than 5 years have passed since last update.

GraphQL Ruby 1.8 Class-based APIへのアップグレード

Last updated at Posted at 2018-06-08

In GraphQL 1.8+, you can use Ruby classes to build your schema. You can mix class-style and .define-style type definitions in a schema.

GraphQL-Ruby 1.8からクラス形式でのGraphQLの型定義が可能になりました

そのアップデート方法に関してドキュメントに記載のないこと、補足事項を記します

Field

GraphQL::FieldResolverに移行します

ベースクラスを定義し、

module Resolvers
  class Base < GraphQL::Schema::Resolver
  end
end

継承します

module Resolvers
  class FindUser < Resolvers::Base
    type Types::UserType null: false
    description("ユーザ情報")
    argument :user_id, ID, "並び順"
    def resolve(user_id:)
      User.find(user_id)
    end
  end
end

利用側でresolver:でセットします

field :findUser, resolver: Resolvers::FindUser

Function

GraphQL::Functionはもともとクラスベースで定義することができましたが、
新しいクラスベースAPIのargumentの記法ではないため、GraphQL::Schema::Mutationに移行します

resolveを書き換える

before

def call(object, inputs_, ctx)
 ...
end

after

def resolve(**inputs)
 some_context_data = context[:some_context_data]
 id = object.some_id
 ...
end
  • 引数はセットしたargumentsがハッシュで渡ります
  • context, objectはGraphQL::Schema::Mutationに定義されています

GraphQLGuard

GraphQL::Schema::Fieldを継承し、field定義時にguardを受け取れるようにします

class Fields::Guardable < GraphQL::Schema::Field
  def initialize(*args, guard: nil, **kwargs, &block)
    @guard = guard
    super *args, **kwargs, &block
  end

  def to_graphql
    field_defn = super
    field_defn.tap { |d| d.metadata[:guard] = @guard }
  end
end

Type側

class Types::MutationType < GraphQL::Schema::Object
  field_class Fields::Guardable
  field :createUser, mutation: Mutations::CreateUser,
                     guard: ->(_obj, _args, _ctx) do
                       ...
                     end
  ...
end
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5