Skip to content

Instantly share code, notes, and snippets.

@fson
Created March 17, 2016 15:10
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save fson/a14f5edf2ae3fb5294dd to your computer and use it in GitHub Desktop.
Save fson/a14f5edf2ae3fb5294dd to your computer and use it in GitHub Desktop.
Recursive GraphQL demo
import { inspect } from 'util';
import {
graphql,
GraphQLEnumType,
GraphQLID,
GraphQLInterfaceType,
GraphQLObjectType,
GraphQLList,
GraphQLNonNull,
GraphQLSchema,
GraphQLString,
} from 'graphql';
const messages = [
{ id: '1', parent: null, content: 'Message 1' },
{ id: '2', parent: '1', content: 'Message 2' },
{ id: '3', parent: '1', content: 'Message 3' },
{ id: '4', parent: '1', content: 'Message 4' },
{ id: '5', parent: '2', content: 'Message 5' },
{ id: '6', parent: '2', content: 'Message 6' },
{ id: '7', parent: '2', content: 'Message 7' },
{ id: '8', parent: '6', content: 'Message 8' },
{ id: '9', parent: '6', content: 'Message 9' },
];
function getMessage(messageID) {
return messages.find((message) => message.id === messageID);
}
function getComments(messageID) {
return messages.filter((message) => message.parent === messageID);
}
const Message = new GraphQLObjectType({
name: 'Message',
fields: () => ({
comments: {
type: new GraphQLList(Message),
resolve(message) {
return getComments(message.id);
},
},
content: {
type: GraphQLString,
},
}),
});
const Query = new GraphQLObjectType({
name: 'Query',
fields: {
message: {
type: Message,
args: {
id: {
type: GraphQLID,
}
},
resolve(root, { id }) {
return getMessage(id);
},
},
},
});
export const Schema = new GraphQLSchema({
query: Query
});
graphql(Schema, `
{
message(id: 1) {
content
comments {
content
comments {
content
comments {
content
}
}
}
}
}
`).then((result) => {
console.log(inspect(result, {depth: null}));
});
{
"name": "recursive-graphql-demo",
"description": "Recursive GraphQL demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "babel-node example.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel": "^5.8.35",
"graphql": "^0.4.18"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment