Skip to content

Instantly share code, notes, and snippets.

@dhavaln
Created June 14, 2018 12:54
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 dhavaln/dd2d142514dea129501996d8932a7cb6 to your computer and use it in GitHub Desktop.
Save dhavaln/dd2d142514dea129501996d8932a7cb6 to your computer and use it in GitHub Desktop.
const express = require('express');
const graphql = require('express-graphql');
const graphqlTools = require('graphql-tools');
const app = express();
// Sample Data
const blogsData = [{_id: 1, title: 'Hello', content: 'World'}];
// Simple Blog schema with ID, Title and Content fields
const typeDefs = `
type Blog{
_id: Int,
title: String!,
content: String!
}
type Query{
blogs: [Blog],
blog(_id: Int): Blog
}
input BlogEntry{
title: String!,
content: String!
}
type Mutation{
createBlog(input: BlogEntry): Blog!,
updateBlog(_id: Int, input: BlogEntry): Blog!,
deleteBlog(_id: Int): Blog!
}
`;
// Resolver to match the GraphQL query and return data
const resolvers = {
Query: {
blogs(root, args, context, info) {
return blogsData
},
blog(root, {_id}, context, info){
return blogsData.find((b) => b._id == _id);
}
},
Mutation: {
createBlog(root, {input}, context, info){
const newBlog = {_id: blogsData.length+1, title: input.title, content: input.content};
blogsData.push(newBlog);
return newBlog;
},
updateBlog(root, {_id, input}, context, info){
const blog = blogsData.find((b) => b._id == _id);
blog.title = input.title;
blog.content = input.content;
return blog;
},
deleteBlog(root, {_id}, context, info){
const blogIndex = blogsData.findIndex((b) => b._id == _id);
const blog = blogsData[blogIndex];
blogsData.splice(blogIndex, 1);
return blog;
}
}
};
// Build the schema with Type Definitions and Resolvers
const schema = graphqlTools.makeExecutableSchema({typeDefs, resolvers});
app.use('/graphiql', graphql({
graphiql: true,
schema
}));
app.listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment