egoz
egoz

Reputation: 364

How to query same field with different types in an Union?

I have the following model

type Duck {
    category: Baz
}

type Foo {
    size: FooSize
}

type Bar {
    size: BarSize
}

union Baz = Foo | Bar

The following query throws an error Validation error of type FieldsConflict: size: they return differing types FooSize and BarSize @ 'duck/category' (it's an intended behaviour as stated here : https://github.com/graphql/graphql-js/issues/53)

{
  duck {
    category {
      ... on Foo {
        size
      }
      ... on Bar {
        size
      }
    }
  }
}

Aliases on size would make the query work, but I can't use them here, because the query results will be passed back to another API which expect Duck.category to have a key named exactly size.

Is there any workaround, or schema refactoring I could use here to get this working ?

Upvotes: 4

Views: 1823

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

At a high level, you can only do three things to resolve that error:

  • Refactor the schema so that the size field is the same type for both types.
  • Alias one or both fields.
  • Only request the field for one of the types.

If you need to pass the response to another API, the easiest thing would be to use aliases and then transform the response client-side before sending it to the API.

Upvotes: 1

Related Questions