🕸️
GraphQLのFieldを条件に応じて返却する方法
方法
- 条件に応じて返却したいFieldと同じ名前のメソッド(=custom method)を定義する。
- 参考
-
https://graphql-ruby.org/fields/introduction.html
by default the custom method name must match the field name
-
https://graphql-ruby.org/fields/introduction.html
- 参考
実装/動作確認
- 使用するType
- book_type.rb
# frozen_string_literal: true module Types class BookType < Types::BaseObject field :id, ID, null: false field :title, String, null: false field :user, UserType, null: false end end
- user_type.rb
- Custom Methodを使う場合
# frozen_string_literal: true module Types class UserType < Types::BaseObject field :id, ID, null: false field :name, String, null: false field :books, [BookType], null: false # custom method def books return [] if object.id == 6 object.books end end end
- 実行結果
# Request { user(id:6) { id name books { id title } } } # Response { "data": { "user": { "id": "6", "name": "user6", "books": [] # custom methodにより[]が返却された } } } # Request { user(id:7) { id name books { id title } } } # Response { "data": { "user": { "id": "7", "name": "user7", "books": [ { "id": "4", "title": "BarBook" } ] } } }
- 実行結果
- Custom Methodを使わない場合
# frozen_string_literal: true module Types class UserType < Types::BaseObject field :id, ID, null: false field :name, String, null: false field :books, [BookType], null: false # custom method # def books # return [] if object.id == 6 # object.books # end end end
- 実行結果
# Request { user(id:6) { id name books { id title } } } # Response { "data": { "user": { "id": "6", "name": "user6", "books": [ # custom methodをコメントアウトしたのでBooksが返却された { "id": "3", "title": "FooBook" } ] } } } # Request { user(id:7) { id name books { id title } } } # Response { "data": { "user": { "id": "7", "name": "user7", "books": [ { "id": "4", "title": "BarBook" } ] } } }
- 実行結果
- Custom Methodを使う場合
- book_type.rb
Discussion