Home » Web Development » JavaScript » Node.js » Nodejs and graphql

About Yatin

Avatar photo
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).

Nodejs and graphql

Hello readers. In this tutorial, we will implement GraphQL with nodejs and focus on creating a hello world application.

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. Nodejs 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": "graphql-helloworld",
  "version": "1.0.0",
  "description": "learning graphql hello world",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "nodejs",
    "graphql",
    "helloworld"
  ],
  "author": "geeks",
  "license": "MIT",
  "dependencies": {
    "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 – Bind the type definition and resolver with the help of graphql

server.js

// example - demonstrating the core graphql js library.

// step1 - importing functions for building the application
let { graphql, buildSchema } = require("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!";
  }
};

// step4 - binding type definition and resolver with the help of graphql

// schema represents the type definition
// rootValue represents the resolver
// source represents the input

// a promise response is returned
graphql({
  schema,
  rootValue,
  source: "{message}"
}).then((response) => {
  console.log(response); // output
});

3. Run the Application

To run the application navigate to the project directory and enter the following command as shown below in the terminal.

Run command

$ npm run start

Once the application is started and executed successfully the below log displaying the hello world message will be shown on the console.

Log

{ data: [Object: null prototype] { message: 'Hello world!' } }

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 in nodejs 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: Nodejs and graphql

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments