Node.js Microservices

In software development microservices are a type of service-oriented architecture. In this architecture the app has a structure containing interconnected services. This architecture enables improved modularity. Applications built using microservices have high scalability, flexibility, systematic data organization, and reliability. Node.js platform is preferred by many developers to build microservices. Node.js is a cross platform, runtime environment used for building server-side, networking apps. Building microservices using Node.js has the benefit of using a rich database of multiple JavaScript modules. This simplifies the application development up to great extent. Also Node.js is single threaded, fast, Event-driven, buffer less, asynchronous, scalable. 

Drawbacks-

They are not automatically the right solution for every project

A big task in microservices is integrating services with a guide to drive the process. 

Another big task is applications and microservices locating each other.

It can sometimes get increased memory resources and testing complexity.


Creating microservices with Node.js

First step is to install Node.js. Then run npm init in your root folder. Command will create a package.json file with some questions about the package which you need to answer.

We will use two packages, Express and Require.


$ npm install express request --save

 

Our packages were downloaded and saved in the node_modules folder. We will create two folders, api and services. 

Create a file server.js in the root folder. Add the following code.


 const express = require('express')

const app = express();

const port = process.env.PORT || 3000;


const routes = require('./api/routes');

routes(app);

app.listen(port, function() {

   console.log('Server started on port: ' + port);

});


Require express in our app and create an app object const app= express();. Then bring route objects from routes.js file in the api folder. Pass the app to the route object and set routes for our app and tell the app to start listening on the port we defined.

Define route for microservies and assign each to a target in controller object. We have two endpoints in our app, one is about returning information about the app, the second has two path parameters which are zip codes of Lego stores. It returns distance in miles.


'use strict';


const controller = require('./controller');


module.exports = function(app) {

   app.route('/about')

       .get(controller.about);

   app.route('/distance/:zipcode1/:zipcode2')

       .get(controller.getDistance);

};


Use strict directive in the code is used for enforcing secure coding practices. Now add controller logic. In the controller file we create a controller object with two properties. These properties handle the requests defined in the route module.


 'use strict';

var properties = require('../package.json')

var distance = require('../service/distance');


var controllers = {

   about: function(req, res) {

       var aboutInfo = {

           name: properties.name,

           version: properties.version

       }

       res.json(aboutInfo);

   },

   getDistance: function(req, res) {

           distance.find(req, res, function(err, dist) {

               if (err)

                   res.send(err);

               res.json(dist);

           });

       },

};


module.exports = controllers;


We define property, about in controller object. It will accept request and response objects. In the getDisttance functionality we will bring a distance module. Pass the requests and response objects to find function in this module. 

External call- We will make a call to a third party API in the file. We are using ZipCodeAPI.com for this. Set the key as an environment variable.

 

var request = require('request');

const apiKey = process.env.ZIPCODE_API_KEY || "hkCt1nW1wF1rppaEmoor7T9G4ta7R5wFSu8l1dokNz8y53gGZHDneWWVosbEYirC";

const zipCodeURL = 'https://www.zipcodeapi.com/rest/';


var distance = {

   find: function(req, res, next) {

       request(zipCodeURL + apiKey 

               + '/distance.json/' + req.params.zipcode1 + '/' 

               + req.params.zipcode2 + '/mile',

       function (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;


To execute the external HTTP request we use the request package. Find function accepts request, response and next objects as parameters. If no error returns the status is 200. The function parses out the body of response into the response object. Your application is ready to execute. Run npm start command. Add parameters to test your app.