Last active
January 18, 2016 06:57
-
-
Save subkitsupport/7dfaa04a78141b68c993 to your computer and use it in GitHub Desktop.
How to GraphQL and Relay
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
const graphql = require('graphql'); | |
const GraphQLRelay = require('graphql-relay'); | |
state.graphql_todos = state.graphql_todos || {}; | |
var nodeDefinitions = GraphQLRelay.nodeDefinitions(function(globalId) { | |
var idInfo = GraphQLRelay.fromGlobalId(globalId); | |
if (idInfo.type == 'Todo') return state.graphql_todos[idInfo]; | |
return null; | |
}); | |
var todoType = new graphql.GraphQLObjectType({ | |
name: 'Todo', | |
interfaces: [nodeDefinitions.nodeInterface], | |
isTypeOf: 'Todo', | |
fields: { | |
id: { type: graphql.GraphQLInt }, | |
isDone: { type: graphql.GraphQLBoolean}, | |
description: { type: graphql.GraphQLString }, | |
} | |
}); | |
var schema = new graphql.GraphQLSchema({ | |
query: new graphql.GraphQLObjectType({ | |
name: 'Query', | |
node: nodeDefinitions.nodeField, | |
fields: { | |
todos:{ | |
type: new graphql.GraphQLList(todoType), | |
resolve: () => Object.keys(state.graphql_todos).map(x => state.graphql_todos[x]) | |
}, | |
todo: { | |
type: todoType, | |
args: { id: { type: graphql.GraphQLInt } }, | |
resolve: (_, args) => state.graphql_todos[args.id] | |
} | |
} | |
}), | |
mutation: new graphql.GraphQLObjectType({ | |
name: 'Mutation', | |
fields: { | |
upsertTodo: { | |
type: todoType, | |
args: { | |
description: { type: new graphql.GraphQLNonNull(graphql.GraphQLString) }, | |
isDone: { type: graphql.GraphQLBoolean } | |
}, | |
resolve: (_, args) => { | |
var key = args.id || Object.keys(state.graphql_todos).length + 1; | |
state.graphql_todos[key] = { id: key, description: args.description, isDone: args.isDone || false}; | |
return state.graphql_todos[key]; | |
} | |
} | |
} | |
}) | |
}); | |
graphql.graphql(schema, req.query.query || req.body.query || req.body) | |
.then(result => res.send(JSON.stringify(result, null, 4))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment