Last active
May 3, 2019 19:05
-
-
Save joeynimu/cfb5f2a4f2f566257a66fbb89de4cde9 to your computer and use it in GitHub Desktop.
Sample code for a graphql server
This file contains hidden or 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 { ApolloServer } = require('apollo-server'); | |
const { generate } = require('shortid'); | |
let data = []; | |
const typeDefs = ` | |
type Query { | |
posts: [post] | |
post(id: String!): post | |
} | |
type post { | |
id: String | |
title: String | |
body: String | |
status: String | |
} | |
type Mutation { | |
addPost(title: String!, body: String!, status: String!): post | |
deletePost(id: String!): post | |
updatePost(id: String!, title: String, body: String, status: String): post | |
} | |
`; | |
const resolvers = { | |
Query: { | |
// READ | |
posts: () => data, | |
post: (parent, args) => data.find(post => post.id === args.id) | |
}, | |
Mutation: { | |
// PUT | |
addPost: (_, { title, body, status }) => { | |
const newPost = { | |
id: generate(), | |
title, | |
body, | |
status | |
}; | |
data = [...data, newPost]; | |
return newPost; | |
}, | |
// DELETE | |
deletePost: (_, { id }) => { | |
const deletedPost = data.find(post => post.id === id); | |
const newData = data.filter(post => post.id !== id); | |
data = newData; | |
return deletedPost; | |
}, | |
// UPDATE | |
updatePost: (_, { id, title, body, status }) => { | |
const newData = data.map(post => { | |
if (post.id === id) { | |
post = { | |
...post, | |
title: title || post.title, | |
body: body || post.body, | |
status: status || post.status | |
}; | |
return post; | |
} | |
return post; | |
}); | |
data = newData; | |
return data.find(post => post.id === id); | |
} | |
} | |
}; | |
const server = new ApolloServer({ typeDefs, resolvers }); | |
server.listen().then(({ url }) => `server running at ${url}`).then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment