@message-queue-toolkit/kafka
Version:
Kafka adapter for message-queue-toolkit
45 lines • 1.7 kB
JavaScript
const DEFAULT_HANDLER_KEY = Symbol('default-handler');
export class KafkaHandlerContainer {
handlers;
messageTypeField;
constructor(topicHandlers, messageTypeField) {
this.messageTypeField = messageTypeField;
this.handlers = this.mapTopicHandlers(topicHandlers);
}
mapTopicHandlers(topicHandlerRouting) {
const result = {};
for (const [topic, topicHandlers] of Object.entries(topicHandlerRouting)) {
if (!topicHandlers.length)
continue;
result[topic] = {};
for (const handler of topicHandlers) {
let handlerKey = this.messageTypeField
? // @ts-expect-error
handler.schema.shape[this.messageTypeField]?.value
: undefined;
handlerKey ??= DEFAULT_HANDLER_KEY;
if (result[topic][handlerKey]) {
throw new Error(`Duplicate handler for topic ${topic}`);
}
result[topic][handlerKey] = handler;
}
}
return result;
}
resolveHandler(topic, messageValue) {
const handlers = this.handlers[topic];
if (!handlers)
return undefined;
let messageValueType = undefined;
// @ts-expect-error
if (this.messageTypeField)
messageValueType = messageValue[this.messageTypeField];
return messageValueType
? (handlers[messageValueType] ?? handlers[DEFAULT_HANDLER_KEY])
: handlers[DEFAULT_HANDLER_KEY];
}
get topics() {
return Object.keys(this.handlers);
}
}
//# sourceMappingURL=KafkaHandlerContainer.js.map