LoginSignup
9
0

More than 5 years have passed since last update.

[graphql-ruby] 型クラスを拡張する

Last updated at Posted at 2018-12-18

型クラスを拡張するって?

graphql_ruby 1.8から型の定義がclassベースになりましたが、実はまだ内部ではレガシーオブジェクトが使われています。
ではどう変換が行われているかというと各型オブジェクト(GraphQL::Schema::Objectとか)に生えているto_graphqlというメソッドがレガシーオブジェクト(GraphQL::ObjectTypeとか)を返すようになっています。
よってこのto_graphqlメソッドをオーバーライドして古い型オブジェクトをいじることで型オブジェクト共通のメタデータなどを設定することができます。これを一言で「型クラスの拡張」と表現しました。

オブジェクト型を拡張してみる

オブジェクト型のto_graphqlをオーバーライドします。

module Types
  class BaseObject < GraphQL::Schema::Object
    def self.to_graphql
      type_defn = super
      type_defn.description = 'hogehoge'
      type_defn
    end
  end
end

適当にユーザーという型を用意しました。

module Types
  class UserType < Types::BaseObject
    field :id, Integer, null: false
    field :name, String, null: false
  end
end

コンソールでオブジェクト型の拡張が確認できました。

[1] pry(main)> Types::UserType.to_graphql.description
=> "hogehoge"

注意点

graphql-rubyは2.0時点でのレガシーオブジェクトの撤廃を予定しており、そのタイミングでto_graphqlメソッドも使えなくなります。
また2.0になる前にgemの挙動が変わる可能性もあるので、この拡張を使う際はその辺に注意する必要があります。

参考

詳しくは公式ドキュメントを参照ください。

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