@villedemontreal/correlation-id
Version:
Express middleware to set a correlation in Express. The correlation id will be consistent across async calls within the handling of a request.
41 lines • 1.72 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCorrelationIdMiddleware = void 0;
const constants_1 = require("../config/constants");
const correlationIdService_1 = require("../services/correlationIdService");
/**
* Correlation ID Middleware
*
* @param filter a filter which is going to be called with the request to see if a
* colleration id scope must be managed or not.
*/
const createCorrelationIdMiddleware = (filter) => {
const correlationIdMiddleware = (req, res, next) => {
if (filter && !filter(req)) {
next();
}
else {
// ==========================================
// If a Correlation ID (cid) exists in the request
// it will be used. Otherwise, a new one is created.
//
// We add the cid to the response!
// ==========================================
let correlationId = req.get('X-Correlation-ID');
if (!correlationId) {
correlationId = correlationIdService_1.correlationIdService.createNewId();
req[constants_1.constants.requestExtraVariables.cidNew] = correlationId;
}
else {
req[constants_1.constants.requestExtraVariables.cidReceivedInRequest] = correlationId;
}
if (!res.headersSent) {
res.set('X-Correlation-ID', correlationId);
}
correlationIdService_1.correlationIdService.withId(next, correlationId);
}
};
return correlationIdMiddleware;
};
exports.createCorrelationIdMiddleware = createCorrelationIdMiddleware;
//# sourceMappingURL=correlationIdMiddleware.js.map