@dalet-oss/express-http-context
Version:
Modern request-scoped storage support for Express.js based on Asynchronous Local Storage.
49 lines • 1.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.set = exports.get = exports.middleware = void 0;
const async_hooks_1 = require("async_hooks");
if (!global.expressHttpContextStorage) {
global.expressHttpContextStorage = new async_hooks_1.AsyncLocalStorage();
}
/**
* Express.js middleware that is responsible for initializing the context for
* each request.
*
* Declared as type 'any' because otherwise Typescript consumers can get tie
* themselves in knots.
*/
const middleware = (_req, _res, next) => {
global.expressHttpContextStorage.run(new Map(), () => next());
};
exports.middleware = middleware;
/**
* Gets a value from the context by key.
*
* Will return undefined if the context has not yet been initialized for this
* request, or if a value is not found for the specified key.
*/
function get(key) {
const store = global.expressHttpContextStorage.getStore();
return store?.get(key);
}
exports.get = get;
/**
* Adds a value to the context by key.
*
* If the key already exists, its value will be overwritten.
* No value will be persisted if the context has not yet been initialized.
*
* Returns the value that was set, or undefined if the context has not yet been
* initialized for this request.
*/
function set(key, value) {
const store = global.expressHttpContextStorage.getStore();
if (store) {
store.set(key, value);
return value;
}
return undefined;
}
exports.set = set;
exports.default = { get, middleware: exports.middleware, set };
//# sourceMappingURL=index.js.map