GraphQL Union and Input Type?

Viewed 18872

Is it possible in GraphQL to have an input type that is also a union?

Something like:

const DynamicInputValueType = new GraphQLUnionType({
  name: 'DynamicInputType',
  types: [GraphQLString, GraphQLFloat, GraphQLInt]
})

but also able to be used as a input for a mutation?

3 Answers

As Artur mentioned, support for union input types is ongoing. Since his post, Tagged Types were proposed as a replacement, which in turn was superseded by the @oneOf directive proposal.

If you need to do this today, an alternative could be to have an input like this:

input AInput {
  a: String!
}

input BInput {
  b: String!
}

input DynamicInputType {
  # 'a' or 'b' — you could make a scalar instead if you'd like 
  type: String! 
  
  # Exactly one of these should be set
  a: AInput
  b: BInput
}

The idea here is that you define one field on this input, and then set type to indicate which field is set. Your resolver would probably need to validate that only the property specified by type is defined.

Related