11import { checkServerIdentity } from "node:tls" ;
2- import {
3- CompressionTypes ,
4- Kafka ,
5- type Producer ,
6- type ProducerConfig ,
7- } from "kafkajs" ;
2+ import { CompressionTypes , Kafka , type Producer } from "kafkajs" ;
83import { compress , decompress } from "lz4js" ;
94
105// CompressionCodecs is not exported properly in kafkajs. Source: https://github.com/tulios/kafkajs/issues/1391
@@ -17,11 +12,10 @@ const { CompressionCodecs } = KafkaJS;
1712 *
1813 * Example:
1914 * ```ts
20- * usageV2 = new KafkaProducer(..)
21- * await usageV2.init()
22- * await usageV2.sendEvents(events)
15+ * kafka = new KafkaProducer(...)
16+ * await kafka.send(topic, events)
2317 * // Non-blocking:
24- * // void usageV2.sendEvents( events).catch(console.error)
18+ * // void kafka.send(topic, events).catch((e) => console.error(e) )
2519 * ```
2620 */
2721export class KafkaProducer {
@@ -94,26 +88,9 @@ export class KafkaProducer {
9488 }
9589 }
9690
97- /**
98- * Connect the producer.
99- * This must be called before calling `sendEvents()`.
100- */
101- async init ( configOverrides ?: ProducerConfig ) {
102- this . producer = this . kafka . producer ( {
103- allowAutoTopicCreation : false ,
104- ...configOverrides ,
105- } ) ;
106- await this . producer . connect ( ) ;
107- }
108-
10991 /**
11092 * Send messages to a Kafka topic.
11193 * This method may throw. To call this non-blocking:
112- *
113- * ```ts
114- * kafka = new KafkaProducer(...)
115- * void kafka.send(topic, messages).catch(console.error)
116- *
11794 * @param topic
11895 * @param messages
11996 * @param configOverrides
@@ -124,13 +101,17 @@ export class KafkaProducer {
124101 /**
125102 * Reference: https://kafka.js.org/docs/producing#producing-messages
126103 */
127- configOverrides ?: {
104+ options ?: {
128105 acks ?: number ;
129106 timeout ?: number ;
107+ allowAutoTopicCreation ?: boolean ;
130108 } ,
131109 ) : Promise < void > {
132110 if ( ! this . producer ) {
133- throw new Error ( "Producer not initialized. Call `init()` first." ) ;
111+ this . producer = this . kafka . producer ( {
112+ allowAutoTopicCreation : options ?. allowAutoTopicCreation ?? false ,
113+ } ) ;
114+ await this . producer . connect ( ) ;
134115 }
135116
136117 await this . producer . send ( {
@@ -139,9 +120,8 @@ export class KafkaProducer {
139120 value : JSON . stringify ( m ) ,
140121 } ) ) ,
141122 compression : this . compression ,
142- acks : - 1 , // All brokers must acknowledge
143- timeout : 10_000 , // 10 seconds
144- ...configOverrides ,
123+ acks : options ?. acks ?? - 1 , // Default: All brokers must acknowledge
124+ timeout : options ?. timeout ?? 10_000 , // Default: 10 seconds
145125 } ) ;
146126 }
147127
0 commit comments