Adding GraphQL to a RESTful API

Building a REST api

$ mkdir express-graphql
$ cd express-graphql
$ npm init -y
$ npm install express
$ mkdir src
// src/app.jsconst express = require('express');
const app = express();
const port = process.env.PORT || 3000;app.listen(port, () => {
console.log(`🏃‍♂️ on port ${port}`);
});
// REST route for authors
const authorRouter = express.Router();
app.use('/api/authors', authorRouter);
// REST route for books
const bookRouter = express.Router();
app.use('/api/books', bookRouter);
// return a list of authors
authorRouter.route('/').get((req, res) => res.json(db.getAuthors()));
// return an author by authorId
authorRouter
.route('/:authorId')
.get((req, res) => res.json(db.getAuthor(req.params.authorId)));
// return a list of books for an author
authorRouter
.route('/:authorId/books')
.get((req, res) => res.json(db.getAuthorBooks(req.params.authorId)));
// a list of books
bookRouter.route('/').get((req, res) => res.json(db.getBooks()));
// a book by bookId
bookRouter
.route('/:bookId')
.get((req, res) => res.json(db.getBook(req.params.bookId)));
// the author of a book
bookRouter
.route('/:bookId/author')
.get((req, res) => res.json(db.getBookAuthor(req.params.bookId)));
const db = require('./db');

Adding GraphQL capabilities to our application

$ npm install apollo-server-express
const { ApolloServer, gql } = require('apollo-server-express');
const typeDefs = /* GraphQL */ gql`
type Author {
id: ID!
name: String
}
type Book {
id: ID!
title: String
}
`;
const typeDefs = /* GraphQL */ gql`type Query {
Authors: [Author]
Author(id: ID!): Author
Books: [Book]
Book(id: ID!): Book
}
type Author {
id: ID!
name: String
}
type Book {
id: ID!
title: String
}
`;
const typeDefs = /* GraphQL */ gql`
type Query {
Authors: [Author]
Author(id: ID!): Author
Books: [Book]
Book(id: ID!): Book
}
type Author {
id: ID!
name: String
}
type Book {
id: ID!
title: String
}
extend type Author {
books: [Book]
}
extend type Book {
author: Author
}

`;
const resolvers = {
Query: {
Authors() {
return db.getAuthors();
},
Author(_, { id }) {
return db.getAuthor(id);
},
Books() {
return db.getBooks();
},
Book(_, { id }) {
return db.getBook(id);
},
},
};
const resolvers = {
Query: {
// ...
},
Author: {
books(author) {
return db.getAuthorBooks(author.id);
},
},

};
Book: {
author(book) {
return db.getAuthor(book.authorId);
},
},
const resolvers = {
Query: {
Authors() {
return db.getAuthors();
},
Author(_, { id }) {
return db.getAuthor(id);
},
Books() {
return db.getBooks();
},
Book(_, { id }) {
return db.getBook(id);
},
},
Author: {
books(author) {
return db.getAuthorBooks(author.id);
},
},
Book: {
author(book) {
return db.getAuthor(book.authorId);
},
},
};
const server = new ApolloServer({
resolvers,
typeDefs,
});
server.applyMiddleware({ app });
query {
Authors {
name
}
Author(id: 2) {
name
}
}
query {
Authors {
id
name
}
Author(id: 2) {
id
name
}
}
query {
Authors {
name
books {
title
}

}
Author(id: 2) {
name
books {
title
}

}
}
query {
Authors {
id
name
books {
title
}
}
Author(id: 2) {
id
name
}
Books {
id
title
}
Book(id: 10) {
id
title
author {
name
}
}
}

A word of caution

const server = new ApolloServer({
resolvers,
typeDefs,
tracing: (process.env.NODE_ENV === 'development'), // tracing
});

Next Steps

--

--

--

Previously Paris and Geneva, currently New York. Can also be found at https://dev.to/arnaud

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to create web application login with JS frontend and Go backend

I Built the Same App With React and Preact. Here are the differences

Preact vs. React

An Introduction to Fiber, an Alternative to Express.js

Fiber Golang Introduction

Testing in Node.js Using Mocha and Chai (Part 2)

How to Write Cleaner React code

How to create a basic calculator using HTML, CSS and JavaScript

Let’s Develop An Online Code Editor/Compiler Like HackerRank

Where is my Video?: A Minor Confusion in Rendering Final Cut Pro Videos

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arnaud Dostes

Arnaud Dostes

Previously Paris and Geneva, currently New York. Can also be found at https://dev.to/arnaud

More from Medium

Why Should You Use Node JS ?

Create a nest js project from scratch (manually)

Learn Nest Js

Get Started with MongoDB Atlas — MongoDB

Read CSV file in Node.js and Typescript