Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Objective

...

The NodeJS Middleware provides the ability to modernize existing API with SOAJ when these APIs are this API is built using NodeJs as a development language.

The middleware exposes several functionality and configuration that SOAJS offers and which can be consumed by the Microservice API upon initialization or during runtime when requests to its APIs arrive.

This page explains the NodeJs middleware; the functionality and configuration that it offers, how to install it and how to use it.

...

  1. How to Install 
  2. Features
    1. Configuration
    2. Functionality
  3. How does it work
    1. on init
    2. on request
  4. Using the Middleware
    1. Initialization State
    2. Runtime State
  5. Examples
    1. NodeJs Express
    2. NodeJs Hapi


1- How to Install

...

Source Code: The SOAJS NodeJs middleware is open source and is available under Github, you can use the following reference to pull the source code → https://github.com/soajs/soajs.nodejs

The middleware is also available as an NPM package and can be download for free.

//
Code Block
languagejsbash
themeMidnight
titleSOAJS NodeJs NPM Package
# install from npm
npm install soajs.nodejs


The middleware can also be used as a dependency in your package.json file

// require it in your project const soajsMW = require('soajs.nodejs');
Code Block
languagejs
themeMidnight
titlePackage.json
{
	"dependencies": {
		"soajs.nodejs": "*"
	}
}


2- Features

...

Once the mw middleware is initialized, the following list of functions will be available to use through 'req.soajs.reg'

...

functionality becomes available:

FunctionTypeInputOutputRemarks
getDatabasesMethoddbName (optional)
  • returns database object if dbName provided
  • returns all core and tenant meta databases otherwise
Mongo Client Driver
getServiceConfigMethod-returns service configuration objectServices Config
getDeployerMethod-returns deployer objectRegistry
getCustomMethod-returns custom objectServices Config
getResourcesMethodresourceName (optional)
  • returns resource object if resourceName provided
  • returns all resources otherwise
Registry
getServicesMethodserviceName (optional)
  • returns service object if serviceName provided
  • returns all services otherwise
Service
getDaemonsMethoddaemonName (optional)
  • returns daemon object if daemonName provided
  • returns all daemons otherwise
Daemon
reloadMethod-void (reload registry only)Registry

This middleware functionality is accessible via the request that is made to the API. The middleware traps the request once it hits the API, injects its functionality and then hands it back to you to add your business logic. 


3-How does it work

...

On Init

...

Using The Middleware requires the following environment variables :to be set prior to starting your service

Environment VariableDescriptionExampleReference

SOAJS_REGISTRY_API

The location of the SOAJS API Gateway along with the maintenance port value that it is using in the environment where the service will run in127.0.0.1:5000/Environment Variables

SOAJS_ENV

the middleware is going to invoke the controller and get the registry. Using the service configuration provided, the mw will auto reload the registry every "serviceConfig.awareness.autoRelaodRegistry"

Once the registry is loaded, the middleware is now ready to act on request.

On request:

Once a request is reached, the SOAJS controller will be passing through the request headers a 'soajsinjectobj' which will be mapped within the middleware to the following standard object:

...

languagejs

...

environment code that this service will run inDEVEnvironment Variables

Once your service starts, the middleware will make a call to the CON and retrieve the registry of the environment, it will cache it in memory.

From this registry, it uses variable autoReloadRegistry (which represents the auto reload duration in seconds) and every time this value is met, the middleware automatically pulls the new version of the registry and updates its cached version.

On request

SOAJS midlleware augments your service by trapping all arriving requests and injecting additional data then hands the updated version of request to your business logic.

The following table illustrates the data that gets injected by the middleware on every request:

PropertyCode SnippetDescriptionReference
Tenant


Code Block
languagejs
titlereq.soajs.tenant
tenant : {
    id : '',
    code : ''

...


...

}


Represents the tenant that is making the call to the API.

Multitenancy

Key

Device

Geo


Code Block
languagejs
titlereq.soajs[ key | device | geo ]
key : {
    config : {},
    iKey : '',
    eKey : ''
},
device : 

...

'',
geo : {}


Represents the key configuration which belongs to the tenant making the call to the API.

Security

Services Config

Application


Code Block
languagejs
titlereq.soajs.application
application : {
    product : '',
    package : '',
    appId : '',
    acl : {},
    acl_all_env : {}

...

}


Represents the application information which belongs to the tenant making the call to the API.

Multitenancy

Access Levels

Package


Code Block
languagejs
titlereq.soajs.package
package :{
    acl :{},
    acl_all_env : {}

...


}


Represents the Productization that the tenant making the call to the API is using.

Productization

Access Levels

URAC


Code Block
languagejs
titlereq.soajs.urac
urac : {}

...


Represents the User whose access token was found in the request.URAC
Awareness


Code Block
languagejs
titlereq.soajs.awareness
awareness : {
    host : '',
    port : '',
    getHost : 'function',
	connect : 

...

'function'
}

...


Represents the SOAJS API Gateway internal network host & port based on the environment where the API is deployed and running in.Request


4- Using the Middleware

...

Require this Middle Ware in your restful nodejs service, and append it to your appOnce you download the middleware, simply require it and instruct the web application server to use it.

Consequently, anywhere in your APIs you can get your soajs object and use the data / functions as follows:, invoke req.soajs to access the data and functions that it offers.

Code Block
languagejs
titleUsing the Middleware with NodeJs
linenumberstrue
// require the mw
const soajsMW = require('soajs.nodejs');

// pass it to your service app
app.use(soajsMW({ 	serviceName : 'testmy_service' }));

//...
use
it// ininvoke yourreq.soajs
requests
app.post('/helloworldfoo', function(req, res) => { 
	var//...

	let soajs = req.soajs;
	// soajs.key.iKey;
	// soajs.reg.getDatabases();console.log( JSON.stringify( soajs, null, 2 ) );

	//...
});
});


5- Examples

...

NodeJs Express

The following code snippets shows a basic example built using NodeJs Express Library and how the SOAJS NodeJs Middleware was added to the code to augment the web server created by express.

Full Example on: https://github.com/soajs/soajs.nodejs.express

Code Block
languagejs
themeMidnight
titleNodeJs Express & SOAJS NodeJs Middleware
linenumberstrue
'use strict';

//Create Express varApp
const express = require('express');
varconst app = express();

//Require SOAJS Middleware for NodeJs
const soajsMW = require('soajs.nodejs');

varconst url = require('url');

//Instruct the Express App to use the SOAJS Middleware
app.use(soajsMW({ serviceName : 'testmy_service' }));

//Invoke the middleware and use it in the Express app API
app.get('/tidbit/hello', function(req, res) => {
var
	let url_parts = url.parse(req.url, true);
var	let query = url_parts.query;

var	let username = query.username;
var	let lastname = query.lastname;

	res.send({
		"message": "Hello`Hello DEMO, I am an EXPRESS service, you are ["+username+" ${username} ] and your last name is : ["+lastname+"]",
dbs ${lastname} ]`,
		"dbs" : req.soajs.reg.getDatabases()
	});
});

//Invoke the middleware and use it in the Express app API
app.post('/tidbit/hello', function(req, res){

var	let response = req.soajs;

	req.soajs.awareness.getHost(function (host) => {

		response.controller = host;
		res.send(response);
	});
});

//Start the Express app and set it to listen on port 4382
app.listen(4382);


NodeJs Hapi

The following code snippets shows a basic example built using NodeJs Hapi Library and how the SOAJS NodeJs Middleware was added to the code to augment the web server created by hapi.

Full Example on: https://github.com/soajs/soajs.nodejs.expresshapi

Hapi Example

Code Block
languagejs
themeMidnight
'use strict';

const Hapiurl = require('hapiurl');
const
soajsMW = require('soajs.nodejs')({serviceName : 'test'});
var url//Create Hapi  App
const Hapi = require('urlhapi');

const server = new Hapi.Server();

//Instruct the Hapi app to listen on port 4380
server.connection({
    host: '0.0.0.0', port: 4380 });

//Require SOAJS Middleware for NodeJs
const soajsMW  port: 4380
});
= require('soajs.nodejs')({serviceName : 'my_service'});

//Instruct the Hapi App to use the SOAJS Middleware
server.ext({
    type: 'onRequest',
    method: function (request, reply) => {
        soajsMW(request, reply, function (err) => {
            if (err) {
                throw err;
            }
            return reply.continue();
        });
    }
});

//Invoke the middleware and use it in the Express app API
server.route({
    method: 'GET',
    path: '/tidbit/hello',     handler: function (request, reply) => {

	    varlet url_parts = url.parse(request.url, true);
	    varlet query = url_parts.query;

	    varlet username = query.username;
	    varlet lastname = query.lastname;

        return reply({
	        		"message": "Hello`Hello DEMO, I am aan HAPIHapi service, you are ["+username+" ${username} ] and your last name is : ["+lastname+"]"
  ${lastname} ]`,
			"dbs" : req.soajs.reg.getDatabases()
        });
    }
});

//Invoke the middleware and use it in the Express app API
server.route({ 	method: 'POST', 	path: '/tidbit/hello', 	handler: function (request, reply) => {

		varlet response = request.soajs;
		request.soajs.awareness.getHost(function (host) => {
			response.controller = host;
			return reply(response);
		});
	}
});

//Start the Hapi app server
server.start((err) => {

    if (err) {
        throw err;
    }
    console.log('Server running at:', server.info.uri);
});

...