@dugongjs/kafkajs
Version:
31 lines (30 loc) • 1.6 kB
JavaScript
import {} from "@dugongjs/core";
import * as changeCase from "change-case";
import { Kafka } from "kafkajs";
import { MessageChannelParticipantKafkaJS } from "../../common/message-broker/message-channel-participator-kafkajs.js";
export class MessageConsumerKafkaJS extends MessageChannelParticipantKafkaJS {
constructor(kafka, consumerConfig, consumerSubscribeTopics, consumerRunConfig) {
super();
this.kafka = kafka;
this.consumerConfig = consumerConfig;
this.consumerSubscribeTopics = consumerSubscribeTopics;
this.consumerRunConfig = consumerRunConfig;
this.consumers = [];
}
generateMessageConsumerIdForAggregate(origin, aggregateType, consumerName) {
const originKebabCase = changeCase.kebabCase(origin);
const aggregateTypeKebabCase = changeCase.kebabCase(aggregateType);
const consumerNameKebabCase = changeCase.kebabCase(consumerName);
return `${originKebabCase}-${aggregateTypeKebabCase}-${consumerNameKebabCase}`;
}
async registerDomainEventMessageConsumer(channelId, consumerId, onMessage) {
const consumer = this.kafka.consumer({ groupId: consumerId, ...(this.consumerConfig ?? {}) });
await consumer.connect();
await consumer.subscribe({ topic: channelId, ...(this.consumerSubscribeTopics ?? {}) });
await consumer.run({ eachMessage: onMessage, ...(this.consumerRunConfig ?? {}) });
this.consumers.push(consumer);
}
async disconnect() {
await Promise.all(this.consumers.map(async (consumer) => consumer.disconnect()));
}
}