TreeMan360
TreeMan360

Reputation: 619

node - continuation-local-storage

I am attempting to use the continuation-local-storage package to access the current express request/response from a point where that is not readily accessible.

I created the following middleware:

var createNamespace = require('continuation-local-storage').createNamespace,
    getNamespace = require('continuation-local-storage').getNamespace;

const domain = 'ns.cls';

exports.configure = function(app) {
  createNamespace(domain);

  app.use(function(req, res, next) {
    exports.set(req, res, "callcontext", { req, res });
    next();
  });
};

exports.set = function(req, res, name, value) {
  var namespace = getNamespace(domain);

  namespace.bindEmitter(req);
  namespace.bindEmitter(res);

  namespace.run(() => namespace.set(name, value));
};

exports.get = function(name) {
  var namespace = getNamespace(domain);
  return namespace.get(name);
};

exports.getCallContext = function() {
  return exports.get("callcontext");
};

However when I attempt to access the context it is undefined:

var localStorage = require('../middleware/local-storage');

module.exports = function(doc, ctx) {
  var callContext = localStorage.getCallContext();
  console.log("value: " + callContext);
};

Does anyone have any ideas?

Thanks in advance,

Mark

Upvotes: 3

Views: 3873

Answers (1)

rojanu
rojanu

Reputation: 1642

createNameSpace should be called once. Also, you have an error on line

exports.set(req, res, "callcontext", { req, res });

should be something like

exports.set(req, res, "callcontext", { key: value });

This is the way I am using it:
to set

var session = require('continuation-local-storage').createNamespace('session')
app.use(function(req, res, next) {
    session.bindEmitter(req);
    session.bindEmitter(res);

    session.run(function() {
      session.set('req', req);
      next();
    });
  });

to get

var session = require('continuation-local-storage').getNamespace('session')
session.get('req') 

Upvotes: 2

Related Questions