Simple connect middleware for accessing data in a request context.
Wrap the request handling in a domain and set and access data for the current request lifecycle only.
All following functions will be run in the created 'namespace'.
The problem
You would like to access data from the request or any middleware in a completely different context.
Due to the async architecture of Node it can become a nightmare to pass the data to all callbacks
is the function chain. This module provides a middleware and an easy to use API to access data
from anywhere in the function chain. No matter if the functions are called async or not.
See the Domain Docs for further information on error handling
for domains.
Install
$ npm install request-context
Example
server config in app.js:
var app = express();
var contextService = require('request-context');
app.use(contextService.middleware('request'));
app.use(function (req, res, next) {
User.findById(req.cookies._id, function (err, user) {
contextService.set('request:user', user);
next();
});
});
app.put(function (req, res, next) {
new Model(req.body).save(function (err, doc) {
res.json(doc);
});
});
[...]
In the Model definition file:
var contextService = require('request-context');
[...]
modelSchema.pre('save', function (next) {
this.modifiedBy = contextService.get('request:user.name');
next();
});
API
middleware
Returns a function that can be used as connect middleware. Takes a string as the name of the namespace as its argument. All functions called after this middleware, async or not, will have read/write access to the context.
var middleware = require('request-context').middleware;
app.use(middleware('some namespace'));
set
, setContext
Set the context for a key
var contextService = require('request-context');
contextService.set('namespace:key', {some: 'value'});
get
, getContext
Get the context for a key
var contextService = require('request-context');
contextService.get('namespace:key.some');
Object Path Syntax
Any value from the context object can be accessed by a simple object dot notation:
var contextService = require('request-context');
contextService.set('namespace:character', {
name: 'Arya Stark',
location: {
name: 'Winterfell',
region: 'North'
}
});
var char = contextService.get('namespace:character');
var region = char.location.region;
contextService.get('namespace:character.name')
contextService.get('namespace:character.location')
contextService.get('namespace:character.location.region')
Documentation
To generate the jsdoc documentation run
$ gulp docs
Test
To run the packaged tests:
$ gulp test