Skip to content

Instantly share code, notes, and snippets.

@tharakabimal
Created February 12, 2017 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tharakabimal/789f925b3ce1ed26022bcc01dcdb2071 to your computer and use it in GitHub Desktop.
Save tharakabimal/789f925b3ce1ed26022bcc01dcdb2071 to your computer and use it in GitHub Desktop.
GraphQL schema
import express from 'express';
import graphqlHTTP from 'express-graphql';
import { buildSchema } from 'graphql';
import bodyParser from 'body-parser';
import Schema from './schema';
let app = express();
let PORT = 3000;
app.use('/graphql', graphqlHTTP({
schema: Schema,
graphiql: true,
formatError: error => ({
message: error.message,
locations: error.locations,
stack: error.stack
})
}));
app.use(bodyParser.text({ type: 'application/graphql' }));
let server = app.listen(PORT, function (){
let host = server.address().address;
let port = server.address().port;
console.log('GraphQL listening at http://%s:%s', host, port);
});
import * as _ from 'underscore'
import mongo from 'promised-mongo';
import {
GraphQLObjectType,
GraphQLSchema,
GraphQLInt,
GraphQLNonNull,
GraphQLString,
GraphQLList
} from 'graphql';
const db = mongo('mongodb://dbeventfly:dbeventfly@ds143539.mlab.com:43539/eventfly');
const userCollection = db.collection('efuser');
const User = new GraphQLObjectType({
name: 'User',
description: 'Represents a user, which could be an admin or a normal user',
fields: () => ({
_id: {type: GraphQLString},
username: {type: GraphQLString}
})
});
const Query = new GraphQLObjectType({
name: 'RootQuery',
fields: {
users: {
type: new GraphQLList(User),
resolve: function() {
return [];
}
}
}
});
const Mutation = new GraphQLObjectType({
name: 'Mutations',
fields: {
createUser: {
type: User,
args: {
_id: {type: new GraphQLNonNull(GraphQLString)},
username: {type: new GraphQLNonNull(GraphQLString)},
},
resolve: function(rootValue, args) {
let user = Object.assign({}, args);
return userCollection.insert(user)
.then(_ => user)
}
}
}
});
const Schema = new GraphQLSchema({
query: Query,
mutation: Mutation
})
export default Schema;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment