by Indrek Lasn

How to setup a powerful API with GraphQL, Koa and MongoDB

Building an API is super fun! Especially when you can leverage modern technologies such as Koa, GraphQL and MongoDB.

Koa is a Node framework, just like Express is a Node framework. We’ll replace Express with Koa since Koa uses async/await syntax over callbacks.

Getting started

The prerequisites for building our API are the following:

  • Node installed
  • Text Editor; I pick Visual Studio Code
  • Terminal
  • Browser

If you have everything you need, please proceed — if not, please install them.

Open your terminal and create a node project, like so:

So far we created our project folder, and initialized a fresh Node project. Now we have the NPM packages available which we can use to install Koa, Mongo, and GraphQL.

Let’s install koa with NPM.

npm i koa

Starting a new Koa server is very simple. All we need is a server.js file and with the following contents:

Start the project with Node:

Installing GraphQL

We need two packages to setup GraphQL with Koa: koa-mount and koa-graphql

npm i koa-mount koa-graphql

GraphQL requires that we pass our initial schema to the GraphQL server. Let’s create one.

We will place the graphQL schema at graphql/schema.js

We pass our initial Query to the buildSchema function

Note: Notice how the argument for the buildSchema is a template literal. I encourage you take a look at this article if this is unfamiliar.

And now we can pass the initial schema to our GraphQL server.

Don’t forget to import koa-mount, koa-graphql, and finally the schema.js.

And then, if we head over to localhost:9000/graphql:

Graphiql — a powerful tool for querying GraphQL on the frontend

Voilà! Initial setup is done. It’s not very useful yet. Ideally, we would like to query GraphQL to save data to our mongodb and read from there.

Setting up MongoDB

In order to read and write with GraphQL, we need a place to read from. This is where Mongo will come in handy. We’ll save and read our data from there.

To make things simpler, we’re gonna use a cloud instance for Mongo. Head over to mlab.com and create a user and a mongo database.

Creating the mongoDB database

Once you’ve created the database, you’ll need a user for the database.

Creating the MongoDB user

Click on the users tab and create a new username with password.

Now you can use the mongoDB paired with Mongoose. The remote url for your database will be something like this:

mongodb://:@ds213615.mlab.com:13615/koa-graphql

Installing mongoose

npm i mongoose

Creating database.js file

We create a dedicated file for database connection.

Note: Make sure you use the username and credentials for your database.

This block of code will try to connect to the remote mongodb. We need to call it somewhere now.

Open server.js and require and call the initDB method.

If we did everything correctly, our console should tell us we connected successfully.

Bravo!

Notice how annoying it is to constantly refresh the server? Let’s solve this with a package called pm2.

PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime, and to facilitate common system admin tasks.

npm install pm2 -g

Add a script called start to our package.json:

Pm2 runs in the background, which frees up our terminal. If you ever want to stop the process, just run pm2 kill. Now we don’t have to restart our server all the time, pm2 does it automatically.

Note: pm2 logs returns the console log statements to the terminal.

MongoDB models

If you ever worked with Mongo, you’re aware that mongoDB lets us create Models for our data. This is a neat way for us to structure how our data will look like.

Create a folder models and inside a file gadgets.js enter:

Note: There is no ID field in our schema. That’s because Mongoose will assign
an ID by default to all schemas.

Great. Let’s also add a collection and some dummy data. The collection name has to map our gadget name in plural, gadgets in this case.

After creating the collection, insert the document in JSON format like so:

That’s all for Mongo. Let’s fetch the data with GraphQL.

GraphQL Queries

GraphQL requires us to create types as well. Think of it like instructions for computers.

graphql/gadgetType.js

Notice we created a graphql type. Inside the fields we can specify the properties of the given type.

Notice the GraphQLObjectType and GraphQLObjectType types we deconstruct from graphQL. These are the primitive types for graphQL.

Creating the graphQL types also grants type-hinting which we’ll use when creating our queries.

Last thing we need to do is refactor our schema.js. We want to query a gadget by id.

Import the Gadget model, gadgetGraphQLType graphql type and GraphQLSchema, GraphQLObjectType, GraphQLString from graphQL to schema.js.

Next we need a root query. Every GraphQL query starts with curly brackets {}:

Voilà! Inside the fields we can specify the gadget query.

Notice the three properties inside the gadget query:

  • type — this is the type of the query, gadgetGraphQLType in this case.
  • args — we can provide arguments to graphql queries, like: gadgets(id: "1")
  • resolve — how do we want to resolve the query? What should happen once the query is being made? Here we return the Gadget model by id.

And finally export it.

The file schema.js file should look like this:

Now head over to http://localhost:9000/graphql and make the query.

This it what we should end up with!

Thanks for reading! ❤ The source code can be found here.

Part II — we’ll discover mutations, and how we can create, delete, update, and read records from our MongoDB with GraphQL.

Keep up to date with me on Twitter

Originally published at strilliant.com on January 27, 2019.

How to improve your asynchronous Javascript code with async and await
How to improve your asynchronous Javascript code with async and await If you've had the chance to observe modern…www.strilliant.comHere are some of the best resources to improve your coding skills
There are lots of high-quality coding tutorials, books, and overall resources on the web. I've gathered the very best…www.strilliant.comHere's yet another list of exciting projects to build
Coding is a skill which is acquired through hard work and passion. To become good at something, one must put in the…www.strilliant.comSupercharge your debugging experience for Node.js
hypothetical: You might check every line of code and try to find a typo. No typo found... next, you might start using…www.strilliant.com