From 61c76e4aba1213995af8352250057bb320cd4537 Mon Sep 17 00:00:00 2001 From: akhoury Date: Sun, 7 Feb 2016 13:16:50 -0500 Subject: [PATCH] add continuation-local-storage support --- package.json | 1 + src/middleware/cls.js | 41 +++++++++++++++++++++++++++++++++++++++++ src/middleware/index.js | 2 ++ 3 files changed, 44 insertions(+) create mode 100644 src/middleware/cls.js diff --git a/package.json b/package.json index b7f7ed676a..0fa110de82 100644 --- a/package.json +++ b/package.json @@ -25,6 +25,7 @@ "connect-mongo": "~1.1.0", "connect-multiparty": "^2.0.0", "connect-redis": "~3.0.2", + "continuation-local-storage": "^3.1.6", "cookie-parser": "^1.3.3", "cron": "^1.0.5", "csurf": "^1.6.1", diff --git a/src/middleware/cls.js b/src/middleware/cls.js new file mode 100644 index 0000000000..31a1065891 --- /dev/null +++ b/src/middleware/cls.js @@ -0,0 +1,41 @@ + +var continuationLocalStorage = require('continuation-local-storage'); + +var NAMESPACE = 'nodebb'; +var namespace = continuationLocalStorage.createNamespace(NAMESPACE); + +var cls = function (req, res, next) { + namespace.run(function() { + var value = {req: req}; + if (process.env.NODE_ENV == 'development') { + value.audit = {created: process.hrtime()}; + } + namespace.set('route', { + req: req, + res: res + }); + next(); + }); +}; + +cls.storage = function () { + return cls.getNamespace(NAMESPACE); +}; + +cls.get = function (key) { + return namespace.get(key); +}; + +cls.set = function (key, value) { + return namespace.set(key, value); +}; + +cls.setItem = cls.set; +cls.getItem = cls.set; +cls.getNamespace = cls.storage; +cls.namespace = namespace; +cls.continuationLocalStorage = continuationLocalStorage; + +module.exports = cls; + + diff --git a/src/middleware/index.js b/src/middleware/index.js index 1cbac02323..3efb1a18f2 100644 --- a/src/middleware/index.js +++ b/src/middleware/index.js @@ -14,6 +14,7 @@ var meta = require('../meta'), compression = require('compression'), favicon = require('serve-favicon'), session = require('express-session'), + cls = require('./cls'), useragent = require('express-useragent'); @@ -73,6 +74,7 @@ module.exports = function(app) { app.use(middleware.addHeaders); app.use(middleware.processRender); + app.use(cls); auth.initialize(app, middleware); return middleware;