2

I'm trying to implement a union type with graphql-ruby.

I followed the official documentation but got the error listed below.

Here is my current code.

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

And here is the graphql query.

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

When I send the query I got the following error.

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

Couldn't find any typo or anything.

Am I missing something??

K-Sato
  • 400
  • 7
  • 26
  • If I'm not wrong, you have a method defined in PostType called `media_item ` which returns mixed object type(like Audio/Movie etc.) Is that correct? – Abhinay Jul 21 '20 at 10:56

1 Answers1

1

You didn't define parent type (superclass of your union).

So add

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

Now your inheritance chain will consistent.

mechnicov
  • 12,025
  • 4
  • 33
  • 56