Build a Simple App with GraphQL, NodeJS, Express, React, and MongoDB - Part 2

Introduction

In this tutorial we’re setting up a simple web application with a GraphQL API built on top of NodeJS, Express, MongoDB, and we’ll top it off on the front-end with some React. In Part 1 of this multi-part tutorial we setup the basic NodeJS Express server. In this Part 2 we’ll start working with GraphQL and get our first version the API up and running.

Setting up the GraphQL API

Install dependencies

In order to get GraphQL working in our NodeJS application we’ll need two packages graphql and express-graphql. Let’s install them with the --save flag because we’ll need them in both the development and production applications:

npm install --save graphql express-graphql

Note: You will need to stop the server to install the dependencies. CTRL + C will stop the server. Then you can restart the server again with the command:

nodemon app.js

Implementing a basic api with GraphQL

All our changes for this Part 2 of the tutorial will be in the app.js file so here we’ll just show you the code and dissect what we’ve done:

const express = require('express') // import express
const bodyParser = require('body-parser') // import body-parser
const graphqlHttp = require('express-graphql') // import graphql to use as middleware
const { buildSchema } = require('graphql') // import the function to build our schema

const app = express() // create express server

app.use(bodyParser.json()) // use body-parser middleware to parse incoming json

app.use('/graphql', graphqlHttp({ // set up our graphql endpoint with the express-graphql middleware
    // build a graphql schema
    schema: buildSchema(`
        type blogQuery {
            blogs: [String!]!
        }

        type blogMutation {
            createBlog(text: String): String
        }

        schema {
            query: blogQuery
            mutation: blogMutation
        }
    `),
    rootValue: {
        blogs: () => {
            return ['blog text', 'another blog text']
        },
        createBlog: (args) => {
            const blogText = args.text
            return blogText
        }
    }, // an object with resolver functions
    graphiql: true // enable the graphiql interface to test our queries
}))

app.listen(5000) // setup server to run on port 5000

Now in our app.js file we did the following ( he comments in the code should help you see exactly where we did each step ):

  • Require express-graphql which will be a middleware to take incoming requests and make sure they go to the right “resolver”. Resolvers are where you take a request and create a response depending on the request. This is where we’ll eventually fetch data from MongoDB and return it but for now we’ll just use dummy responses.
  • Required the buildSchema function from graphql so that we can build the GraphQL schema.
  • We deleted our test route.
  • We implemented the single endpoint /graphql that will accept all incoming requests and told express to use the graphqlHttp middleware.
  • We built the schema for the GraphQL api. We have defined a blogs route that will return an array of Strings (non-nullable) and a createBlog route that accepts a String as an argument and returns a String. We mapped these endpoints to resolvers inside the rootValue object. In these resolvers we decided what to return, which for now is just dummy data.
  • We enabled that graphiql interface on this endpoint so when we hit http://localhost:5000/graphql we get a very useful interface that allows us to test our queries.

Test the GraphQL Api

Because we’ve enabled graphiql when we go to http://localhost:5000/graphql we get this:

Image from Gyazo

From here we can test our queries. This is how we’d test our blogs endpoint:

query {
  blogs
}

This is the result you should get:

{
  "data": {
    "blogs": [
      "blog text",
      "another blog text"
    ]
  }
}

Image from Gyazo

Now let’s test the createBlog endpoint with this query:

mutation {
  createBlog(text: "new blog text content")
}

This is the result that we expect and that we get:

{
  "data": {
    "createBlog": "new blog text content"
  }
}

Image from Gyazo

Conclusion

At this point we’ve setup the structure for an API with GraphQL. Although it is only returning dummy data at this point it will end up being a fully functional API that will perform multiple operations and pull data from a MongoDB database. We hope this tutorial helped you learning about GraphQL and how to set it up and we hope you continue following along as we flesh out this application.

Build a Simple App with GraphQL, NodeJS, Express, React, and MongoDB – Part 1

Build a Simple App with GraphQL, NodeJS, Express, React, and MongoDB – Part 2

Build a Simple App with GraphQL, NodeJS, Express, React, and MongoDB – Part 3

Build a Simple App with GraphGL, NodeJS, Express, React, and MongoDB – Part 4

Pilot the ObjectRocket Platform Free!

Try Fully-Managed Redis,
MongoDB & Elasticsearch

Get Started

OR

Try CockroachDB
in Beta

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.