@allan1361/iota-big3-sdk-middleware
Version:
🏆 A+ Grade Certified Enterprise Middleware Framework - Phase 3 Certified (90/100) with advanced resilience patterns, comprehensive type safety, and production-ready observability
71 lines • 3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRequestIdMiddleware = createRequestIdMiddleware;
exports.fastifyRequestId = fastifyRequestId;
exports.getRequestId = getRequestId;
exports.correlateLogger = correlateLogger;
const uuid_1 = require("uuid");
const DEFAULT_CONFIG = {
headerName: 'X-Request-ID',
generator: () => (0, uuid_1.v4)(),
trustProxy: false,
attributeName: 'id'
};
function createRequestIdMiddleware(config = {}) {
const options = { ...DEFAULT_CONFIG, ...config };
return function requestIdMiddleware(req, res, next) {
let requestId = options.trustProxy && req.headers[options.headerName.toLowerCase()]
? String(req.headers[options.headerName.toLowerCase()])
: options.generator();
if (options.trustProxy && req.headers[options.headerName.toLowerCase()]) {
const providedId = String(req.headers[options.headerName.toLowerCase()]);
if (!/^[\w-]{8,128}$/.test(providedId)) {
requestId = options.generator();
}
}
req[options.attributeName] = requestId;
const correlationHeader = req.headers['x-correlation-id'];
if (correlationHeader) {
req.correlationId = String(correlationHeader);
}
res.setHeader(options.headerName, requestId);
res.locals = res.locals || {};
res.locals.requestId = requestId;
next();
};
}
async function fastifyRequestId(fastify, options = {}) {
const config = { ...DEFAULT_CONFIG, ...options };
fastify.decorateRequest('id', '');
fastify.decorateRequest('correlationId', '');
fastify.addHook('onRequest', async (request, reply) => {
let requestId = config.trustProxy && request.headers[config.headerName.toLowerCase()]
? String(request.headers[config.headerName.toLowerCase()])
: config.generator();
if (config.trustProxy && request.headers[config.headerName.toLowerCase()]) {
const providedId = String(request.headers[config.headerName.toLowerCase()]);
if (!/^[\w-]{8,128}$/.test(providedId)) {
requestId = config.generator();
}
}
request[config.attributeName] = requestId;
const correlationHeader = request.headers[config.correlationHeader.toLowerCase()];
if (correlationHeader) {
request.correlationId = String(correlationHeader);
}
reply.header(config.headerName, requestId);
});
}
function getRequestId(req, options = {}) {
return req[options.attributeName] || options.generator();
}
function correlateLogger(logger, req, options = {}) {
const requestId = getRequestId(req, options);
const correlationId = req.correlationId;
return logger.child({
requestId,
...(correlationId && { correlationId })
});
}
exports.default = createRequestIdMiddleware;
//# sourceMappingURL=request-id-middleware.js.map