3

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

TreeMan360
  • 589
  • 1
  • 5
  • 16

1 Answers1

2

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') 
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
rojanu
  • 1,592
  • 5
  • 20
  • 34
  • I believe this won't work unless you're not getting yourself into using promises... which is hard to avoid. I think every promise destroys that run context. – kboom Jan 03 '17 at 18:02
  • What is the use of `bindEmitter` here ? Won't this work without it. – t0il3ts0ap Feb 08 '19 at 15:56