How to use unions with GraphQL buildSchema

Viewed 2331

Here is how I am using a GraphQL schema string to create a schema and attach it to my Express server:

var graphql = require('graphql');
var graphqlHTTP = require('express-graphql');
[...]
    return graphqlHTTP({
      schema: graphql.buildSchema(schemaText),
      rootValue: resolvers,
      graphiql: true,
    });

This is all very basic use of the modules. It works well and is quite convenient until I want to define a union:

union MediaContents = Photo|Youtube

type Media {
  Id: String
  Type: String
  Contents: MediaContents
}

I have found no way to make this work, querying Contents does what it has to do, returns the correct object but fails with the message Generated Schema cannot use Interface or Union types for execution.

Is it at all possible to use unions when using buildSchema ?

2 Answers

In case you are returning an object with all the information, you can add a __typename field in your object. Like this:

return {
  token: res.token,
  user: {
    __typename: 'YOUR_TYPE_HERE',
    ...res.user
  }
};
Related