Software

Explain Node.js Microservices Architecture

Pinterest LinkedIn Tumblr
Node js Microservices Architecture

Developing apps is not just about fulfilling clients’ requirements. It also includes building a large system where all these requirements can function harmoniously. Developers go through various challenges like maintenance of the codebase, implementing new features, managing user roles, bug fixing, etc.

Monolith apps commonly face these problems, and to solve them, distributed systems are used. These systems include different components that function independently. A distributed app consists of multiple microservices working together to make the app perform as per the requirements. Here’s a step-wise guide that helps you build Microservices using Node.js. Let’s learn more about microservices in detail in this article.

Microservices and Node.JS- Basic understanding

Microservices are like SOA (Service-Oriented Architecture). In the process of software app development, various interconnected microservices are used to structure the app.

Microservices make the app architecture is made using lightweight protocols. These services are seeded in the Node.JS architecture. Microservices will disintegrate the project into more minor services and create better modularity.

As compared to the predecessor- monolithic architecture, these services are more beneficial. Here, developers do not need to stuff all components in one container. Microservices provides features like:

  • High scalability
  • Greater flexibility
  • Systematic organization of data
  • Reliability
  • Time optimization

Developing JS apps using microservices will help you focus on building mono-functional modules included with clearly defined operations and accurate interfaces. The app development becomes agile, and continuous testing requirement is mitigated.

When one builds apps using monolithic architecture, the whole app needs deployment with every update. On the other side, microservices will have no dependency on framework type, technique, or any programming language used for building them. You can release REST-ful APIs for communication and different services are the requisite for microservice architecture.

Let’s now know about how Node.JS helps in developing Microservices.

Node.JS

Node.JS is the platform that most developers prefer to build JS microservices. In a JS engine, Node is an open-source, cross-platform runtime environment that is used for developing server-side and networking apps. Node.JS is written in JS and is executed on MS Windows, Linux, and OS X OSs in the Node.JS runtime.

Here are some reasons for using the Node.JS framework for building microservices:

Node.js consists of a rich database of various JS modules that simplifies app development at a greater scale. Software developers prefer Node.js for developing I/O bound apps, JSON API apps, single-page apps, real-time data-intensive apps, and data streaming apps.

Here are the primary advantages of using Node.js:

  • Super-fast in code execution on V8 JS engine
  • Along with event looping, the single-threaded, non-blocking mechanism is used by the server to respond to various requests
  • Events in Node.js is a system notification that helps the app server to collect the response of an API call that was working previously
  • Non-synchronous and non-blocking Node.JS libraries will move to the next API and will not wait for the return data of the previous API.
  • Other benefits of Node.js are that it is highly scalable, the app will buffer less, and the program gets licensed under this framework.

Tech giants like Uber, Microsoft, PayPal, Yammer, eBay, etc. are using Node.js development.

Let’s learn more about how to build microservices using Node.JS.

Developing Microservices with Node.JS

Here are the steps used to develop microservices with Node.JS:

Assessing the business requirements

For building a microservice, let us assume that one business needs a service that identifies two ZIP codes and provides an approximate distance between these points.

The distance is measured in miles, and you will need validation techniques for identifying the ZIP code and distance calculation. The requirement needs to configure the external calls of the API. And it is necessary to duplicate calls and cost-effectively construct the process. An internal cache is used for this process.

Initialization

To begin with, firstly you have to ensure that Node.JS is installed. If you do not have it installed, you can follow the steps mentioned in its documentation to install it.

In the terminal:

  • Create one directory named microservice, and enter that directory
  • Use NPM to collect the required packages of dependency (Request and Express) Express is a backend framework and Request is a package that enables communication with external APIs.
  • To install packages in the terminal, you can use the following command:
npm i express request - - save
  • The i in the above statement is for ‘install’, and the – – save attribute enables the addition of packages as dependencies in the package.json file.

Setting the server up

From the three architectures of our project, build an entry file known as server.js which will be executed when the server starts. Add the below code in the server.js file:

const express = require('express');
const app = express();
app.use(express.json());
const routes = require('./api_routes/routes');
routes(app);
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Listening to port http://localhost:${port}`);
});

Routes are made available in the primary file by requiring it and passing the instance in the routes object.

After this step, we will see how to define routes. When the server runs, the app will begin listening on port 3000 or other specified PORT env variable.

Specify the routes

In the API-routes folder, one has to create a file named routes.js and add the below code into it:

'use strict';
const controller = require('../controllers/appController');
module.exports = (app) => {
  app.route('/about').get(controller.about);
  app.route('/distance/:zipcode1/:zipcode2').get(controller.getDistance);
}

The routes file makes two endpoints: /distance/:zipcode1/:zipcode2 and /About

The first one, /distance, is used to compute the distance in miles from zipcode1 to zipcode 2 with the use of an external API that returns the distance for us.

And the /about point will help us specify the app details.

Implementing endpoints in the controller file will give us the next step.

Creating the controller

A Node.JS controller obj interprets the user intent and manages requests received in the routes module developed earlier. Make a new file named controllers or appController.js and add the below-given code in it:

'use strict';

const properties = require('../package.json');
const distance = require('../service/distance');

const controllers = {
	about: (req, res) => {
    	const aboutInfo = {
        	name: properties.name,
        	version: properties.version,
    	}
    	res.json(aboutInfo);
	},
	getDistance: (req, res) => {
    	distance.find(req, res, (err, dist) => {
        	if (err)
            	res.send(err);
        	res.json(dist);
    	});
	},
};
module.exports = controllers;

This controller file has two different functions known as getDistance() and about().

In the getDistance function, there are two arguments, response and request. It will call the find API present in the services folder.

And in about() it accepts two arguments, the same as getDistance, a request, and a response. The version and name are stored in the properties of package.json.

Establish the Call

For creating this instance code, we have stored API keys and zipCodeURL in the env variable and named them ZIPCODE_API_URL and ZIPCODE_API_KEY.

Here’s the code to make the microservices:

const request = require('request');
const apiKey = process.env.ZIPCODE_API_KEY ||
  "hkCt1nW1wF1rpaEm7T9G4ta7R5wFSu8l1dokNz8y53gGZHDneWWVo"; 
//here place your key
const zipCodeURL = process.env.ZIPCODE_API_URL;
var distance = {
    find: (req, res, next) => {
        request(zipCodeURL + apiKey +
            '/distance.json/' + req.params.zipcode1 + '/' +
            req.params.zipcode2 + '/mile',
            (error, response, body) => {
                if (!error && response.statusCode == 200) {
                    response = JSON.parse(body);
                    res.send(response);
                } else {
                    console.log(response.statusCode + response.body);
                    res.send({
                        distance: -1
                    });
                }
            });
    }
};
module.exports = distance;

This first loads the request package for processing the external HTTP request and loading API Key & zipCodeURL from the environment variable.

The find() gets a request object and specifies one callback function to get a call when it receives the response. If the function has zero errors and the response has HTTP status 200, it means success.

Final Execution

If you arrive at the final execution step successfully, you should be able to execute the whole program by running the npm start in the final terminal of the project.

If everything is smooth, you can hit the /about the endpoint of the project and look at output somewhat similar to the following:

{“name”: “microservices”, “version”: “1.0.0”}

Moving forward when the /distance is hit, here’s the output that one can see on the screen:

{“distance”: 452.892}

This is it.

Concluding words

When you follow these steps carefully, you will be easily able to create a microservice using Node.js. For more such informative posts, stay in touch. Till then, happy reading!

Write A Comment

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