Sometimes you need piece of data, most of the time request/response objects, between different events of a request where it is generally not accessible. Continuation Local Storage is a package to access the current express request/response object from a point where that is not readily accessible. 

Problem

Suppose you have a rest API (/users) that serves the user data. The handler of this API calls the service layer to get user data. The service layer calls your facade layer to get data from either directly from the database or from third party URL. After getting the data from different sources, facade layer combines the data and return to service layer that further returned to the actual API.

Now API layer accepts the cookie that contains some token to validate the request. The same token is required at facade layer. One way is to pass the token extracted from cookie at API layer to service layer that further will pass to facade layer.

In some cases, there can be other layers and events in which you need the same token or user data. Passing data, layers to layers is not a good practice and not a cleaner way.

So to sort the same problem Continuation Local Storage (CLS) comes into the picture.

What is Continuation Local Storage (CLS)?

Continuation Local Storage is a package to access the current express request/response object from a point where that is not readily accessible. It works like thread-local-storage in multithreading programming like java. As nodejs is single threaded it supports events/callbacks instead of multi-threads. And to achieve the same It uses the concept of **namespace**.

Node.js is asynchronous and uses an event loop to manage the asynchronicity, AsyncListener allows you to write software that can keep hold of information across callbacks.

What is Thread Local Storage (TLS)?

From Wikipedia

Thread Local storage (TLS) is a computer programming method that uses static or global memory local to a thread.

Setup

Let’s get started with Continuation Local Storage

1) Install the continuation-local-storage package

npm install continuation-local-storage --save

2) Create namespace that will hold the objects that we want to access at global level

let app = express();
let cls = require('continuation-local-storage');
let namespace = cls.createNamespace('com.domain');

3) Define middleware that will bind the request and response object to namespace

app.use((req, res, next) => {
   var nameSpace = cls.getNamespace('com.domain');
   // wrap the events from request and response
   nameSpace.bindEmitter(req);
   nameSpace.bindEmitter(res);
 
   // run middleware in the scope of the namespace that we have created
   nameSpace.run(() => {
       // set data to the namespace that we want to access in different events/callbacks
       namespace.set('data', "any_data");
       next();
   });
});

4) Now this data can be accessed at any layer. For demo, logging the data that was set in the namespace

//logger.ts

var getNamespace = require("continuation-local-storage").getNamespace;
let nameSpace = getNamespace("com.domain");
let data = nameSpace.get("any_data");
console.log("data : ", data);

1 Comment

Aman · December 15, 2017 at 6:42 pm

awesome

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

NodeJS

Interceptor: Intercepting third party Request and Response on the Server side

In the previous post, we have seen 1) What are the interceptors? 2) How to intercept HTTP calls at the client side in Angular2 and Angular4? On the server side, there are scenarios where we need Read more…

Interview Questions

Nodejs Interview Questions

Important Interview Questions for Node.js 1) What is Nodejs ? 2) What is NPM ? 3) Different types of API’s exist in Node (api methods)? 4) What is event looping ? 5) What is event Read more…

NodeJS

NPM : Node Package Manager

NPM is a node package manager for the JavaScript programming language.It is the world’s largest software registry. It consistes of a command line client also called NPM and also the default package manager for the Read more…