GraphQL-RubyでUnion型を実装する方法

GraphQLにおけるUnion型は、Object型のリストを表現します。

実装方法は、ドキュメントを参考にすると以下の通りです。

簡易的にUnionを試すためUserクラスにcommentsメソッドを実装していますが、本来はSTIやCTIなどの実装を表現する場合に利用します。それ以外で利用例があれば是非、コメントを頂けると幸いです。

query {
  user {
    nodes {
     id
     commnets {
       __typename
       ... on Post {
        color
      }
      ... on Image {
        url
      }
    }
  }
}
module Types
  class User
    field :id, ID, null: false
    field :comments, Types::CommentSubject, null: false
    
    def comments
      if [true, false].sample
        object.blog_post # BlogPost Model
      else
        object.image # Image Model
      end
    end
  end
end
module Types
  class CommentSubject < Types::BaseUnion
    description "Objects which may be commented on"
    possible_types Types::Post, Types::Image
  
    # Optional: if this method is defined, it will override `Schema.resolve_type`
    def self.resolve_type(object, context)
      if object.is_a?(BlogPost)
        Types::Post
      else
        Types::Image
      end
    end
  end
end

Union型の実装時に、possible_typesで少なくとも一つの型を宣言する必要があります。

初めてのGraphQL ―Webサービスを作って学ぶ新世代API

初めてのGraphQL ―Webサービスを作って学ぶ新世代API

  • 作者:Eve Porcello,Alex Banks
  • 出版社/メーカー: オライリージャパン
  • 発売日: 2019/11/13
  • メディア: 単行本(ソフトカバー)