@message-in-the-middle/core
Version:
Framework-agnostic middleware pattern for message queue processing. Core package with all middlewares.
75 lines • 3.01 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CorrelationIdOutboundMiddleware = exports.CorrelationIdInboundMiddleware = void 0;
exports.getCorrelationContext = getCorrelationContext;
exports.getCorrelationId = getCorrelationId;
const async_hooks_1 = require("async_hooks");
const crypto_1 = require("crypto");
const correlationStorage = new async_hooks_1.AsyncLocalStorage();
function getCorrelationContext() {
return correlationStorage.getStore();
}
function getCorrelationId() {
return correlationStorage.getStore()?.correlationId;
}
class CorrelationIdInboundMiddleware {
options;
constructor(options = {}) {
this.options = {
fieldName: options.fieldName ?? 'correlationId',
parentFieldName: options.parentFieldName ?? 'parentCorrelationId',
generator: options.generator ?? (() => (0, crypto_1.randomUUID)()),
useAsyncLocalStorage: options.useAsyncLocalStorage ?? true,
injectIntoOutbound: options.injectIntoOutbound ?? true,
logger: options.logger,
};
}
async process(context, next) {
const existingId = context.message?.[this.options.fieldName];
const correlationId = (typeof existingId === 'string' && existingId)
? existingId
: this.options.generator();
const parentId = context.message?.[this.options.parentFieldName];
const parentCorrelationId = typeof parentId === 'string' ? parentId : undefined;
context.metadata.correlationId = correlationId;
if (parentCorrelationId) {
context.metadata.parentCorrelationId = parentCorrelationId;
}
if (this.options.logger) {
this.options.logger.log('Correlation ID assigned', correlationId);
}
if (this.options.useAsyncLocalStorage) {
const correlationContext = {
correlationId,
parentCorrelationId,
timestamp: Date.now(),
};
await correlationStorage.run(correlationContext, async () => {
await next();
});
}
else {
await next();
}
}
}
exports.CorrelationIdInboundMiddleware = CorrelationIdInboundMiddleware;
class CorrelationIdOutboundMiddleware {
options;
constructor(options = {}) {
this.options = {
fieldName: options.fieldName ?? 'correlationId',
generator: options.generator ?? (() => (0, crypto_1.randomUUID)()),
};
}
async processOutbound(context, next) {
const existingId = getCorrelationId();
const messageWithId = context.message;
if (!messageWithId[this.options.fieldName]) {
messageWithId[this.options.fieldName] = existingId ?? this.options.generator();
}
await next();
}
}
exports.CorrelationIdOutboundMiddleware = CorrelationIdOutboundMiddleware;
//# sourceMappingURL=correlation-id.middleware.js.map