@parthar/express-cls-context
v1.0.1
Published
CLS based context for Express requests
Downloads
3
Maintainers
Readme
Express CLS Context
CLS based context for Express Requests
Installation
$ npm install @parthar/express-cls-context --save
Usage
// setup expressjs middleware
var expressCls = require("@parthar/express-cls-context");
var express = require("express");
var app = express();
...
app.use(expressCls.middleware);
// everything after this has access to the context via setContext & getContext
// e.g., set the user-context after-login
app.post('/login',
passport.authenticate('local'),
function (req, res) {
expressCls.setContext('user', req.user);
}
);
// or, after deserialization of session
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
expressCls.setContext('user', user);
done(err, user);
});
});
// access the user somewhere deep within some user-service
function someService(arg1, arg2, callback) {
var user = expressCls.getContext('user');
}
// get the CLS namespace to bind to a function
// this is sometimes needed for code that does not comply to CLS
// e.g., refer https://github.com/Automattic/mongoose/issues/3313
function saveUser(data, callback) {
var user = expressCls.getContext('user');
var clsCallback = expressCls.getNamespace().bind(callback);
mongooseModel.save(clsCallback);
}