2023-03-01 13:03:54 +01:00
|
|
|
import { CompressionCodecs, CompressionTypes } from 'kafkajs'
|
|
|
|
import SnappyCodec from 'kafkajs-snappy'
|
2023-10-10 16:13:05 +02:00
|
|
|
import { HighLevelProducer } from 'node-rdkafka'
|
2023-03-01 12:03:13 +01:00
|
|
|
|
|
|
|
import { defaultConfig } from '../src/config/config'
|
2023-05-04 15:02:44 +02:00
|
|
|
import { produce as defaultProduce } from '../src/kafka/producer'
|
2023-03-01 12:03:13 +01:00
|
|
|
|
2023-03-01 13:03:54 +01:00
|
|
|
CompressionCodecs[CompressionTypes.Snappy] = SnappyCodec
|
|
|
|
|
2023-03-01 12:03:13 +01:00
|
|
|
let producer: HighLevelProducer
|
|
|
|
|
|
|
|
beforeAll(async () => {
|
|
|
|
producer = await createKafkaProducer()
|
|
|
|
})
|
|
|
|
|
|
|
|
afterAll(async () => {
|
|
|
|
await new Promise((resolve, reject) =>
|
|
|
|
producer?.disconnect((error, data) => {
|
|
|
|
return error ? reject(error) : resolve(data)
|
|
|
|
})
|
|
|
|
)
|
|
|
|
})
|
|
|
|
|
|
|
|
export async function createKafkaProducer() {
|
|
|
|
producer = new HighLevelProducer({
|
|
|
|
'metadata.broker.list': defaultConfig.KAFKA_HOSTS,
|
2023-05-04 15:02:44 +02:00
|
|
|
'linger.ms': 0,
|
2023-03-01 12:03:13 +01:00
|
|
|
})
|
|
|
|
|
|
|
|
await new Promise((resolve, reject) =>
|
|
|
|
producer.connect(undefined, (error, data) => {
|
|
|
|
return error ? reject(error) : resolve(data)
|
|
|
|
})
|
|
|
|
)
|
|
|
|
|
|
|
|
return producer
|
|
|
|
}
|
|
|
|
|
2024-03-25 14:01:15 +01:00
|
|
|
export async function produce({
|
|
|
|
topic,
|
|
|
|
message,
|
|
|
|
key,
|
|
|
|
waitForAck,
|
|
|
|
}: {
|
|
|
|
topic: string
|
|
|
|
message: Buffer | null
|
|
|
|
key: string
|
|
|
|
waitForAck: boolean
|
|
|
|
}) {
|
2023-03-01 12:03:13 +01:00
|
|
|
producer = producer ?? (await createKafkaProducer())
|
2024-03-25 14:01:15 +01:00
|
|
|
await defaultProduce({ producer, topic, value: message, key: Buffer.from(key), waitForAck })
|
2023-03-01 12:03:13 +01:00
|
|
|
}
|