Search code examples
graphqlgraphql-js

Given a graphql.js schema, how can I find all the variants of a particular union type?


Suppose I have a graphQL schema built like this:

var { buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Human = // some object type
  type Droid = // another object type
  union SearchResult = Human | Droid
  type Query {
    result: SearchResult
  }
`);

const searchResultVariants = ?

Now I am looking for a way to programmatically find out all the variants of SearchResult type in the same program for the given schema, is there a way for that? Thank you


Solution

  • Get the abstract type (interface or union) in question:

    const searchResultType = schema.getType('SearchResult');
    

    then get its possible types:

    const possibleTypes = schema.getPossibleTypes(searchResultType);
    

    possibleTypes will an array of GraphQLObjectType objects.

    You can also test whether a particular type is a possible type of an abstract type using isPossibleType.