Brendan
Brendan

Reputation: 3493

GraphQL defining union before type

I am trying to define my GraphQL schema using the graphql library. The schema I am trying to achieve, simplified, is this:

type TypeA {
  fieldA: String
  fieldAorB: TypeAorB
}

type TypeB {
  fieldB: String
}

union TypeAorB = TypeA | TypeB

I am struggling to figure out how to achieve this using the graphql library, given that I can't define the union type before the other types are defined.

Hopefully this snippet highlights my predicament.

import * as graphql from "graphql";

const typeA = new graphql.GraphQLObjectType({
  name: "TypeA",
  fields: { 
    fieldA: { type: graphql.GraphQLString },
    fieldAorB: { type: [???] } // what goes here?
  },
});
const typeB = new graphql.GraphQLObjectType({
  name: "TypeB",
  fields: {
    fieldB: { type: graphql.GraphQLString }
  },
});

const typeAorB = new graphql.GraphQLUnionType({
  name: "TypeAorB",
  types: [typeA, typeB],
});

Upvotes: 0

Views: 39

Answers (1)

Brendan
Brendan

Reputation: 3493

After re-reading the documentation:

When two types need to refer to each other, or a type needs to refer to itself in a field, you can use a function expression (aka a closure or a thunk) to supply the fields lazily.

fields can be a closure that can be resolved later.

i.e.,

const typeA = new graphql.GraphQLObjectType({
  name: "TypeA",
  fields: () => ({ // note: closure, not object.
    fieldA: { type: graphql.GraphQLString },
    fieldAorB: { type: typeAorB }
  }),
});

Upvotes: 1

Related Questions