-
-
Save NetOpWibby/7f3a751b91fcb77739166cea69e8999c to your computer and use it in GitHub Desktop.
Recursive GraphQL demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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})); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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