|
1 | | -const { Kafka } = require('kafkajs'); |
| 1 | +const KafkaJS = require('kafkajs'); |
2 | 2 |
|
3 | 3 | const { KafkaProcessor } = require('./kafka-processor'); |
4 | 4 |
|
5 | | -const kafka = new Kafka({ |
6 | | - clientId: 'ship', |
7 | | - brokers: ['kafka:9092'], |
8 | | -}); |
| 5 | +class Kafka { |
| 6 | + constructor(config) { |
| 7 | + this.kafka = new KafkaJS.Kafka(config); |
9 | 8 |
|
10 | | -const processors = { |
11 | | - user: new KafkaProcessor(kafka, { groupId: 'ship' }, { topic: 'user' }), |
12 | | -}; |
| 9 | + this.producer = this.kafka.producer(); |
| 10 | + this.processors = {}; |
| 11 | + } |
13 | 12 |
|
14 | | -async function run() { |
15 | | - await Promise.all(Object.values(processors).map((p) => p.run())); |
16 | | -} |
| 13 | + addProcessor(topic, consumerConfig, subscribeConfig = { topic }) { |
| 14 | + if (this.processors[topic]) { |
| 15 | + throw new Error(`Processor for "${topic}" topic already exists`); |
| 16 | + } |
| 17 | + |
| 18 | + this.processors[topic] = new KafkaProcessor(this.kafka, consumerConfig, subscribeConfig); |
| 19 | + return this; |
| 20 | + } |
| 21 | + |
| 22 | + async run() { |
| 23 | + await this.producer.connect(); |
| 24 | + await Promise.all(Object.values(this.processors).map((p) => p.run())); |
| 25 | + } |
17 | 26 |
|
18 | | -async function send({ event, data, ...record }) { |
19 | | - const producer = kafka.producer(); |
20 | | - await producer.connect(); |
21 | | - await producer.send({ |
22 | | - ...record, |
23 | | - messages: [ |
24 | | - { value: JSON.stringify({ event, data }) }, |
25 | | - ], |
26 | | - }); |
27 | | - await producer.disconnect(); |
| 27 | + async send({ event, data, ...record }) { |
| 28 | + await this.producer.send({ |
| 29 | + ...record, |
| 30 | + messages: [ |
| 31 | + { value: JSON.stringify({ event, data }) }, |
| 32 | + ], |
| 33 | + }); |
| 34 | + } |
28 | 35 | } |
29 | 36 |
|
30 | | -module.exports = { |
31 | | - kafka, |
32 | | - processors, |
33 | | - run, |
34 | | - send, |
35 | | -}; |
| 37 | +const kafka = new Kafka({ clientId: 'ship', brokers: ['kafka:9092'] }); |
| 38 | + |
| 39 | +kafka.addProcessor('user', { groupId: 'ship' }); |
| 40 | + |
| 41 | +module.exports = kafka; |
0 commit comments