Folks, Trying to set a transaction id for each api call. The following works:
var cls = require('continuation-local-storage');
var uuid = require('node-uuid');
var namespace = cls.createNamespace('foo');
var tokenMiddleware = function tokenMiddleware(req, res, next){
namespace.bindEmitter(req);
namespace.bindEmitter(res);
namespace.run(function() {
namespace.set('tid', tid);
next();
});
};
Now, when I try adding additional information (returned from mongo), it loses context:
var cls = require('continuation-local-storage');
var uuid = require('node-uuid');
var namespace = cls.createNamespace('foo');
var tokenMiddleware = function tokenMiddleware(req, res, next){
mongo.fetchId(authId, function (result) {
namespace.bindEmitter(req);
namespace.bindEmitter(res);
namespace.run(function() {
namespace.set('tid', tid);
namespace.set('somethingfromDB',result.something);
next();
});
});
};
the transaction id is not available further down, its undefined... How come does the first example work, and the second one does not?
What am I doing wrong? I suspect the problem has to do something with the next() context. Express v4.
Thanks!
I have had a similar problem using express. As far as I can tell, the mongo module overwrites the request and response functions. Once you are inside the database call you will find that these objects are no longer what you expect them to be. My solution was to split this into 2 separate functions, which allows you to explicitly pass them to the db function.
var tokenMiddleware = function tokenMiddleware(req, res, next){
var callDB = function (req, res, namespace) {
mongo.fetchId(authId, function (result) {
namespace.bindEmitter(req);
namespace.bindEmitter(res);
namespace.run(function() {
namespace.set('tid', tid);
namespace.set('somethingfromDB',result.something);
next();
});
});
});
callDB(req, res, namespace)
};
Try setting SomethingfromDB in a promise. Refer https://www.promisejs.org/ or try assigning the tid after somethingfromdb is set
var cls = require('continuation-local-storage');
var uuid = require('node-uuid');
var namespace = cls.createNamespace('foo');
var tokenMiddleware = function tokenMiddleware(req, res, next){
mongo.fetchId(authId, function (result) {
namespace.bindEmitter(req);
namespace.bindEmitter(res);
namespace.run(function() {
namespace.set('somethingfromDB',result.something);
namespace.set('tid', tid);
next();
});
});
};
hope this helps