How do i create a graphql schema for a self referencing data hierarchy?
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;
}
}
}
});
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;
}
}
})
});