LoginSignup
0
0

More than 3 years have passed since last update.

GraphQL-RubyでInterfaceTypeを活用する

Posted at

Graphql-RubyでInterfaceTypeを使う方法を説明します。

Interface Typeって?

Interface TypeはObjectTypeから呼び出して継承させることができます。

と言ってもよくわからんので、実際にActiveRecordInterfaceを作ってみます。

active_record_interface.rb
module InterfaceTypes
  module ActiveRecordInterface
    include InterfaceTypes::BaseInterface
    description 'Active Record Interface'

    field :id, ID, null: false
    field :updated_at, GraphQL::Types::ISO8601DateTime, null: false
    field :created_at, GraphQL::Types::ISO8601DateTime, null: false
  end
end

上記はactive recordを利用すると必ず生成されるカラムを定義しています。
ここで定義したInterfaceをObject Typeで継承することができます。

object_type.rb
# frozen_string_literal: true

module ObjectTypes
  class UserType < ObjectTypes::BaseObject
    implements InterfaceTypes::ActiveRecordInterface

    field :name, String, null: false
  end
end

interfaceをimplementsすることで、idやupdate_atをわざわざ書かなくてもfieldとして定義してくれるので、非常に便利です。
interface typeに他にもいろいろ使い道がありそうですが、まだ使ってないのでこれからいろいろ試したいと思います。

0
0
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
0
0