Search code examples
graphqlrelayjs

How do i create a graphql schema for a self referencing data hierarchy?


This doesnt work because the type refers to its self in the routes field definition:

  var routeType = new GraphQLObjectType({
  name: 'MessageRoute',
  fields: {
    name: {
      type: GraphQLString
    },
    routes: {
      type: new GraphQLList(routeType),
      resolve: (route) => {
        return route.routes;
      }
    }
  }
});

so how do I do it?


Solution

  • A GraphQL type can refer to itself (or refer to another type defined later in a file) by defining fields as a function that returns an object rather than an object. The function will be called after the page has been fully parsed.

    For your example:

    var routeType = new GraphQLObjectType({
      name: 'MessageRoute',
      fields: function () {
        return {
          name: {
            type: GraphQLString
          },
          routes: {
            type: new GraphQLList(routeType),
            resolve: (route) => {
              return route.routes;
            }
          }
        };
      }
    });
    

    Or, if you're using ES6, a nice shorthand for this using arrow functions:

    var routeType = new GraphQLObjectType({
      name: 'MessageRoute',
      fields: () => ({
        name: {
          type: GraphQLString
        },
        routes: {
          type: new GraphQLList(routeType),
          resolve: (route) => {
            return route.routes;
          }
        }
      })
    });