SammoSampson
SammoSampson

Reputation: 245

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?

Upvotes: 12

Views: 6303

Answers (2)

Lee Byron
Lee Byron

Reputation: 1894

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;
      }
    }
  })
});

Upvotes: 22

Shalkam
Shalkam

Reputation: 783

I'd like to point out that you can use a function for any property inside an object using Javascript getter.

So instead of wrapping the whole fields property within a function you can use a function just for the type property like this:

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

Upvotes: 3

Related Questions