@zakyyudha/http-context-middleware
Version:
HTTP context middleware using Node.js AsyncLocalStorage
48 lines (47 loc) • 1.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const index_1 = require("../index");
/**
* Create Express middleware for HTTP context
* @param options - Configuration options
* @returns Express middleware function
*/
function expressContextMiddleware(options = {}) {
const { includeReqRes = false } = options;
return (req, res, next) => {
// Create initial context
const context = {
requestId: req.headers['x-request-id'] || index_1.HttpContext.generateRequestId(),
startTime: Date.now(),
route: req.path,
method: req.method,
};
// Optionally include req/res objects
if (includeReqRes) {
context.req = req;
context.res = res;
}
// Run the middleware chain with this context
index_1.HttpContext.runWithContext(context, () => {
// Add a response hook to capture timing information
const originalEnd = res.end;
// Use any type for the function to avoid TypeScript errors
// but maintain the same behavior
res.end = function (...args) {
// Calculate request duration
const startTime = index_1.HttpContext.get('startTime') || 0;
const requestDuration = Date.now() - startTime;
index_1.HttpContext.set('requestDuration', requestDuration);
// Optionally set the request ID in the response headers
if (context.requestId) {
res.setHeader('X-Request-ID', context.requestId);
}
// Forward all arguments to the original function
// Ensure we meet the expected signature requirements
return originalEnd.apply(this, args);
};
next();
});
};
}
exports.default = expressContextMiddleware;