Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 782
SammoSampson Avatar asked Sep 13 '15 15:09

SammoSampson


People also ask

Does GraphQL have a schema?

Your GraphQL server uses a schema to describe the shape of your available data. This schema defines a hierarchy of types with fields that are populated from your back-end data stores. The schema also specifies exactly which queries and mutations are available for clients to execute.

What two pieces make up a GraphQL schema?

In an app using GraphQL, there are two core pieces: your GraphQL schema and your GraphQL server (independent from your HTTP server). The schema is attached to the server so that when a request comes in, the server understands how to process it.

What other types can be used in a GraphQL schema?

A GraphQL schema can contain more than just the scalar types. The two most used types are query and mutation types. Every GraphQL service will have a query type. This is the entry point to a GraphQL schema.


1 Answers

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;
      }
    }
  })
});
like image 80
Lee Byron Avatar answered Sep 20 '22 03:09

Lee Byron