-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
73 lines (63 loc) · 1.51 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { KafkaConsumer, KafkaProducer } from "./kafka";
import { Kafka, logLevel } from "kafkajs";
let instance, consumer: KafkaConsumer | undefined, producer: KafkaProducer | undefined;
const errorTypes = ["unhandledRejection", "uncaughtException"];
errorTypes.map((type) => {
process.on(type, async (e) => {
try {
console.log(`process.on ${type}`);
console.error(e);
if (consumer) await consumer.disconnect();
if (producer) await producer.disconnect();
process.exit(0);
} catch (_) {
process.exit(1);
}
});
});
Object.values<NodeJS.Signals>(["SIGHUP", "SIGINT", "SIGTERM"]).map((type) => {
process.once(type, async () => {
try {
if (consumer) await consumer.disconnect();
if (producer) await producer.disconnect();
} finally {
process.kill(process.pid, type);
}
});
});
export default (options) => {
if (instance) {
return instance;
}
const {
consumerConfig,
producerConfig,
client = new Kafka({
logLevel: logLevel.ERROR,
brokers: [options.kafkaHost],
clientId: options.serviceId,
ssl: options.ssl || false,
sasl: options.sasl,
}),
...rest
} = options;
consumer = consumerConfig
? new KafkaConsumer({
...consumerConfig,
client,
...rest,
})
: undefined;
producer = producerConfig
? new KafkaProducer({
...producerConfig,
client,
...rest,
})
: undefined;
instance = {
consumer,
producer,
};
return instance;
};