DevOps

Express-js and graphql

Hello readers. In this tutorial, we will implement GraphQL with express-js.

1. Introduction

GraphQL is an API syntax that defines how to fetch data from one or more databases. It was developed by Facebook to optimize the RESTful api calls.

  • It is a data query and manipulation language for api’s. It is faster, simple, and easier to implement
  • It follows the client-driven architecture and gives a declarative way to fetch and update the data
  • It has a graphical structure where objects are represented by nodes and edges represent the relationship between the nodes
  • Provides high consistency across all platforms
  • It doesn’t have any automatic caching system

1.1 Application components in GraphQL

In graphql, there are two types of application components.

  • Server-side components
  • Client-side components

1.1.1 Service-side components

The server-side component allows parsing the queries coming from the graphql client applications and consists of 3 components i.e. query, resolver, and schema. Apollo is the most popular graphql server.

ComponentDescription
QueryA query is a client request made by the graphql client for the graphql server. It is used to fetch values and can support arguments and points to arrays. field and arguments are two important parts of a query
ResolverHelps to provide directions for converting graphql operation into data. Users define the resolver functions to resolve the query to the data. They help to separate the db and api schema thus making it easy to modify the content obtained from the db
SchemaIt is the center of any graphql server implementation. The core block in a schema is known as a type

1.1.2 Client-side components

The client-side components represent the client which is a code or a javascript library that makes the post request to the graphql server. It is of two types i.e.

  • GraphiQL – Browser-based interface used for editing and testing graphql queries and mutations
  • Apollo client – State management library for javascript that enables local and remote data management with graphql. Supports pagination, prefetching data, and connecting the data to the view layer

1.2 Advantages and Disadvantages

Graphql offers several advantages and disadvantages. E.g.

1.2.1 Advantages

  • Faster than other communication api’s as it allows to cut down the request by choosing only specific fields in the query
  • No over and under fetching problems as it only fetches the exact and specific data in a single request
  • Follows the hierarchial structure where relationships between objects are defined in a graphical structure
  • It is strongly typed language as each level of query corresponds to a particular type and each type describes a set of available fields

1.2.2 Disadvantages

  • Query and caching complexity
  • Rate limiting

1.3 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Fig. 1: Verifying node and npm installation

2. Express-js and graphql

To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE. Let a take a quick peek at the project structure.

Fig. 2: Project structure

2.1 Setting up project dependencies

Navigate to the project directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Replace the generated file with the code given below –

package.json

{
  "name": "express-graphql",
  "version": "1.0.0",
  "description": "learning graphql in expressjs",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "graphql",
    "express",
    "express-graphql",
    "nodejs"
  ],
  "author": "geeklearner",
  "license": "MIT",
  "dependencies": {
    "express": "^4.18.1",
    "express-graphql": "^0.12.0",
    "graphql": "^16.5.0"
  }
}

Once the file is replaced trigger the below npm command in the terminal window to download the different packages required for this tutorial.

Downloading dependencies

npm install

2.2 Setting up implementation file

Create a file in the root directory responsible to handle the application startup and perform the graphql operations. Here we will –

  • Step 1 – Import the functions for building the application
  • Step 2 – Write the type definition
  • Step 3 – Write the resolver
  • Step 4 – Setting up the expressjs configuration for the application

index.js

// example - demonstrating the graphql and expressjs

let express = require("express");

// step1 - importing functions for building the application
let { buildSchema } = require("graphql");
let { graphqlHTTP } = require("express-graphql");

// step2 - type definition

// schema wraps up all build definitions
let schema = buildSchema(`
  type Query {
    message: String
  }
`);

// step3 - resolver
let rootValue = {
  message: () => {
    return "Hello world!";
  }
};

let app = express();

// url - http://localhost:3005/graphql
app.use(
  "/graphql",
  graphqlHTTP({
    schema,
    rootValue,
    graphiql: true
  })
);

// driver code
const port = 3005;
app.listen(port, () => {
  console.log(`Application listening on port ${port}`);
});

3. Run the Application

To run the application navigate to the project directory and enter the following command as shown below in the terminal. The application will be started successfully on the port number – 3005.

Run command

$ npm run start

Once the application is started successfully open the browser and hit the below endpoint to view the graphql view. Enter the query as shown below and you should see the hello world output.

Application endpoint

open the browser and hit the below url. the page will open the graphql dashboard
http://localhost:3005/graphql

in the input enter the query below and you be able to see the output as in the demo image
{
  message
}
Fig. 3: Application demo

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

4. Summary

In this tutorial, we saw a brief introduction to graphql and practical implementation of graphql in the express-js application. You can download the source code from the Downloads section.

5. Download the Project

This was a tutorial to graphql in a nodejs application.

Download
You can download the full source code of this example here: Expressjs and graphql

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button