@awesomeniko/kafka-trail
Version:
A Node.js library for managing message queue with Kafka
99 lines • 3.49 kB
JavaScript
import Kafka, { CompressionTypes } from "kafkajs";
import { UnableDecreasePartitionsError } from "../custom-errors/kafka-errors.js";
import { CustomPartitioner } from "./custom-partitioner.js";
import { KTKafkaBroker } from "./kafka-broker.js";
class KTKafkaProducer extends KTKafkaBroker {
constructor(params) {
super(params);
const { createPartitioner, logger } = params;
let customPartitioner = createPartitioner;
if (!customPartitioner) {
customPartitioner = CustomPartitioner.roundRobin;
}
this.
createPartitioner: customPartitioner,
allowAutoTopicCreation: false,
});
this.
this.
}
getAdmin() {
return this.
}
init() {
return Promise.all([this.
}
destroy() {
return Promise.all([this.
}
async createTopic(topicConfig) {
this.
topicName: topicConfig.topic,
topicConfig,
}, "Resolving topics...");
try {
const topicMetadata = await this.
const currentTopic = topicMetadata.topics.find((topicMetadata) => topicMetadata.name === topicConfig.topic);
if (!currentTopic) {
throw new Kafka.KafkaJSProtocolError('Topic not found');
}
if (topicConfig.numPartitions === currentTopic.partitions.length) {
return;
}
if ((topicConfig.numPartitions || 0) > currentTopic.partitions.length) {
await this.
topicPartitions: [
{
topic: topicConfig.topic,
count: topicConfig.numPartitions || 0,
},
],
});
this.
}
else {
throw new UnableDecreasePartitionsError();
}
this.
}
catch (e) {
if (e instanceof Kafka.KafkaJSProtocolError) {
await this.
topics: [topicConfig],
waitForLeaders: true,
});
}
else {
this.
throw e;
}
}
}
async sendSingleMessage(params) {
const { topicName, messageKey, value, headers } = params;
await this.
topic: topicName,
compression: CompressionTypes.LZ4,
messages: [
{
key: messageKey ?? null,
value,
headers,
},
],
});
}
async sendBatchMessages(params) {
const { topicName, messages } = params;
await this.
topic: topicName,
compression: CompressionTypes.LZ4,
messages,
});
}
}
export { KTKafkaProducer };
//# sourceMappingURL=kafka-producer.js.map