Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS TransactionID with Continuation-local-storage

Tags:

node.js

Folks, I'd like to implement transaction id tracking in NodeJS. After reading this article, https://datahero.com/blog/2014/05/22/node-js-preserving-data-across-async-callbacks/, I get the following error from the code:

var server = express();
var getNamespace = require('continuation-local-storage').getNamespace
var namespace = getNamespace('com.me')
var uuid = require('node-uuid');

// create a transaction id for each request
server.use(function(req, res, next) {
    var tid = uuid.v4();

    // wrap the events from request and response
    namespace.bindEmitter(req);
    namespace.bindEmitter(res);

    // run following middleware in the scope of
    // the namespace we created
    namespace.run(function() {

        // set tid on the namespace, makes it
        // available for all continuations
        namespace.set('tid', tid);
        next();
    });
});

error:

TypeError: Cannot call method 'bindEmitter' of undefined
like image 326
Cmag Avatar asked May 22 '26 10:05

Cmag


1 Answers

Folks, Here is the proper code that works:

var express = require('express');
var server = express();

var cls = require('continuation-local-storage');
var namespace = cls.createNamespace('com.me');

var uuid = require('node-uuid');

// create a transaction id for each request
server.use(function(req, res, next) {
    var namespace = cls.getNamespace('com.me');
    var tid = uuid.v4();

    // wrap the events from request and response
    namespace.bindEmitter(req);
    namespace.bindEmitter(res);

    // run following middleware in the scope of
    // the namespace we created
    namespace.run(function() {

        // set tid on the namespace, makes it
        // available for all continuations
        namespace.set('tid', tid);
        next();
    });
});
like image 94
Cmag Avatar answered May 25 '26 00:05

Cmag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!