vadim.blog | Vadim Nicolai

CRUD App Using GraphQL Apollo Server, MongoDB And Angular

October 31st, 2018

Until GraphQL came out, RESTful API was the most popular choice for client-server communication. REST has been defined about 20 years ago, in context of problems from that time. As applications became more complex and new devices came around, new problems has emerged and REST wasn’t able to solve them in a performant way. One common scenario is: we want to display on homepage a list of articles and for each article we want to have it’s author name and avatar or email. With REST api we need to make few requests to achieve this: one to get the list of articles with author IDs and then other few requests to get information about each author. With GraphQL this can be done in single query:

javascript
// a GraphQL query
articles {
edges {
title
author {
fullname
email
}
}
}
// a GraphQL query result
{
"data": {
"articles": {
"edges": [
{
"title": "Article title",
"author": {
"fullname": "author fullname",
"email": "[email protected]"
}
},
{
"title": "Article title",
"user": {
"fullname": "author fullname",
"email": "[email protected]"
}
},
{
"title": "Article title",
"user": {
"fullname": "author fullname",
"email": "[email protected]"
}
}
]
}
}
}

In order to understand better how GraphQL works, I made a simple app. GraphQL Apollo Server is acting like an interface between MongoDB plus external API and the client. As client-side consumer I’ve chosen Angular, but it can be any other solution which Apollo Client is supporting.

Robin Wieruch has done a great job explaining all details about how to setup correctly Apollo GraphQL in his lengthy and throughout tutorial. I will focus on main aspects of implementation.

On server I have defined schema:

javascript
import {gql} from 'apollo-server-express'
export default gql`
extend type Query {
task(name: String!): Task
getAllTasks: [Task]
}
extend type Mutation {
addTask(name: String): Task!
updateTask(id: String, name: String): Task
removeTask(id: String): Task
}
type Task {
id: String
name: String
}
`

And resolver:

javascript
export default {
Query: {
getAllTasks: async () => {
const tasks = await Task.find()
const issues = await getIssues()
return [...tasks, ...issues]
},
task: (parent, arg) => {
return {name: arg.name}
},
},
Mutation: {
addTask: (parent, {name}) => {
return new Promise((resolve, reject) => {
Task.create({name}, (err, result) => {
const task = R.pipe(
R.pickAll(['_id', 'name']),
renameKeys({_id: 'id'}),
)(result.toJSON())
if (err) return reject(err)
resolve({id: task.id.toString(), name: task.name})
})
})
},
removeTask: async (parent, {id}) => {
try {
const removedtask = await Task.findByIdAndRemove(id).exec()
return removedtask
} catch (e) {
throw new Error('Error: ', e)
}
},
updateTask: async (parent, {id, name}) => {
try {
const updatedTask = await Task.findByIdAndUpdate(id, {
$set: {name},
}).exec()
return updatedTask
} catch (e) {
throw new Error('Error: ', e)
}
},
},
}

On client we consume GraphQL via queries and mutations:

javascript
import gql from 'graphql-tag'
export const addTask = gql`
mutation addTask($name: String!) {
addTask(name: $name) {
id
name
}
}
`
export const getAllTasks = gql`
query {
getAllTasks {
id
name
}
}
`
export const removeTask = gql`
mutation removeTask($id: String!) {
removeTask(id: $id) {
id
name
}
}
`
export const updateTask = gql`
mutation updateTask($id: String!, $name: String!) {
updateTask(id: $id, name: $name) {
id
name
}
}
`

All code is available here.

More Articles

React Compound Components

There are situations when we need to pass props to multiple children components. Manually passing props makes app tightly coupled and less…
October 26th, 2018
© 2021 vadim.blog | Vadim Nicolai