使用 graphql-ruby 实现联合类型

Implementing union type with graphql-ruby

我正在尝试使用 graphql-ruby 实现联合类型。

我按照 official documentation 进行操作,但遇到了下面列出的错误。

这是我当前的代码。

module Types
  class AudioClipType < Types::BaseObject
    field :id, Int, null: false
    field :duration, Int, null: false
  end
end

module Types
  class MovieClipType < Types::BaseObject
    field :id, Int, null: false
    field :previewURL, String, null: false
    field :resolution, Int, null: false
  end
end

module Types
  class MediaItemType < Types::BaseUnion
    possible_types Types::AudioClipType, Types::MovieClipType

    def self.resolve_type(object, context)
      if object.is_a?(AudioClip)
        Types::AudioClipType
      else
        Types::MovieClipType
      end
    end
  end
end

module Types
  class PostType < Types::BaseObject
    description 'Post'
    field :id, Int, null: false
    field :media_item, Types::MediaItemType, null: true
  end
end

这里是 graphql 查询。

{
  posts {
    id
    mediaItem {
      __typename
      ... on AudioClip {
        id
        duration
      }
      ... on MovieClip {
        id
        previewURL
        resolution
      }
    }
  }
}

发送查询时出现以下错误。

Failed to implement Post.mediaItem, tried:
 - `Types::PostType#media_item`, which did not exist
 - `Post#media_item`, which did not exist
 - Looking up hash key `:media_item` or `"media_item"` on `#<Post:0x007fb385769428>`, but it wasn't a Hash

To implement this field, define one of the methods above (and check for typos

找不到任何拼写错误或任何内容。

我是不是漏掉了什么??

您没有定义父类型(联合的超类)。

所以添加

class Types::BaseUnion < GraphQL::Schema::Union
end

现在您的继承链将保持一致。