@dugongjs/kafkajs
Version:
45 lines (44 loc) • 1.52 kB
JavaScript
import { Partitioners } from "kafkajs";
import { MessageChannelParticipantKafkaJS } from "../../common/message-broker/message-channel-participator-kafkajs.js";
export class MessageProducerKafkaJS extends MessageChannelParticipantKafkaJS {
constructor(kafka, producerConfig) {
super();
this.kafka = kafka;
this.producerConfig = producerConfig;
this.isConnected = false;
this.producer = this.kafka.producer({
createPartitioner: Partitioners.DefaultPartitioner,
...this.producerConfig
});
}
async publishMessage(_, messageChannelId, message) {
this.ensureConnected();
await this.producer.send({
topic: messageChannelId,
messages: [message]
});
}
async publishMessages(_, messageChannelId, messages) {
this.ensureConnected();
await this.producer.send({
topic: messageChannelId,
messages
});
}
async connect() {
await this.producer.connect();
this.isConnected = true;
}
async disconnect() {
await this.producer.disconnect();
this.isConnected = false;
}
ensureConnected() {
if (!this.producer) {
throw new Error("Producer is not created. Call create() method before publishing messages.");
}
if (!this.isConnected) {
throw new Error("Producer is not connected. Call connect() method before publishing messages.");
}
}
}