Using GraphQL in Express JS

mhmmdysf

Muhammad Yusuf

Posted on July 14, 2021

Using GraphQL in Express JS

GraphQL is a useful query language for your API. But it can be intimidating because they bring the complexity upfront as there are a lot that has to be set up before we can create our first query. I hope this article will be useful and understandable. Let's get started!

First things first, we'll need to require our module to our file and put some basic express boilerplate, let's say it's called app.js:

const express = require('express')
const app = express()
const { graphqlHTTP } = require('express-graphql')
const port = 3000

// We'll put everything here later

// This code below must be on the last part of the file
app.listen(port, () => {
  console.log('Listening on port:', port)
})
Enter fullscreen mode Exit fullscreen mode

Then we'll create our first and (maybe) only route in this article:

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}))
Enter fullscreen mode Exit fullscreen mode

Instead of using (req, res) => {} to the callback we put an invoked graphqlHTTP function, so we can let the graphql do its thing. Inside the graphqlHTTP, we put a object that contains option to switch the graphiQL interface on, and schema that we'll create later on.

So what's a schema?

Schema defines a hierarchy of types with fields that are populated from your back-end data stores. The most basic components of a GraphQL schema are object types for query and mutation (optional), which just represent a kind of object you can fetch from your service, and what fields it has.

In the simplest way, we might represent the object types like this:

{
  name: 'Book',
  fields: {
    title: { type: GraphQLString },
    author: { type: GraphQLString }
  }
}
Enter fullscreen mode Exit fullscreen mode

What's GraphQLString? It's a type that can only be recognized by graphQL instead of regular String in javascript. They have other types as well like GraphQLInt, GraphQLList, and GraphQLObjectType. And we can define them like this:

const {
  GraphQLSchema, // for base schema type
  GraphQLString,
  GraphQLInt,
  GraphQLList,
  GraphQLObjectType
} = require('graphql')
Enter fullscreen mode Exit fullscreen mode

Now before we make our schema, we can create our own type first by putting the book object from earlier.

const BookType = new GraphQLObjectType({
  name: 'Book',
  fields: {
    title: { type: GraphQLString },
    author: { type: GraphQLString }
  }
})
Enter fullscreen mode Exit fullscreen mode

Then we create our query object and prepare it with a small dummy data:

let dummyBooks = [
  { title: 'Harry Potter', author: 'JK Rowling' },
  { title: 'Lord of The Rings', author: 'JRR Tolkien' },
  { title: 'Sherlock Holmes', author: 'Arthur Conan Doyle' }
]

const queryType = new GraphQLObjectType({
  name: 'Book query',
  fields: function () {
    return {
      // we called it books so we can type 'books' later on
      books: {
        type: new GraphQLList(BookType),
        resolve: function () {
          return dummyBooks
        }
      }
    }
  }
})
Enter fullscreen mode Exit fullscreen mode

Query object requires fields function that returns an object. The object itself contains properties of what we want to find via the query later on. And each has to have type and resolve. type property defines the type returned to us users and resolve gives the actual data, which is dummyBooks.

Lastly, we can define our schema like this:

const schema = new GraphQLSchema({
  query: queryType
})
Enter fullscreen mode Exit fullscreen mode

Running the file

Now we can run this from terminal:

node app.js
Enter fullscreen mode Exit fullscreen mode

Type this in the browser:

localhost:3000/graphql
Enter fullscreen mode Exit fullscreen mode

Now you'll see this:
GraphiQL

There are two main parts in the screen, the white part on the left is the query editor, we can crate our query there. And the gray part on the right side will show the result of query done in the left.

Now we can create our first query:

query {
  books {
    title
  }
}
Enter fullscreen mode Exit fullscreen mode

Notice there's no author in the query, and we'll get the data exactly like our query format:

{
  "data": {
    "books": [
      {
        "title": "Harry Potter"
      },
      {
        "title": "Lord of The Rings"
      },
      {
        "title": "Sherlock Holmes"
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

source: https://graphql.org/learn/

💖 💪 🙅 🚩
mhmmdysf
Muhammad Yusuf

Posted on July 14, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Using GraphQL in Express JS
graphql Using GraphQL in Express JS

July 14, 2021