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'.
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. Note that the domain module is pending deprecation!
$ npm install request-context
server config in app.js:
const app = ;const contextService = ;// wrap requests in the 'request' namespace (can be any string)app;// set the logged in user in some auth middlewareapp;// save a model in put requestsapp;// always use an default express/connect error handling middleware// it will be called if any errors occur in the domain// seeapp;// start server etc....
In the Model definition file:
var contextService = ;...// set the user who made changes to this document// note that this method is called async in the document contextmodelSchema;
Also available on the github pages.
middlewareReturns 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 = middleware;app;
setContextSet the context for a key on the context created by the middleware.
var contextService = ;contextService;contextService;
getContextGet the context for a key on the context created by the middleware.
var contextService = ;contextService; // returns 'other'
Any value from the context object can be accessed by a simple object dot notation:
var contextService = ;// set an object on the namespacecontextService;// this will return the complete objectvar char = contextService;// work with the objectvar region = charlocationregion;// this will return 'Arya Stark'contextService;// this will set the region to 'Westeros'contextService;
The documentation is available on the github pages. To generate the jsdoc documentation run
$ gulp docs
To run the packaged tests:
$ gulp test