-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKafkaService.js
62 lines (55 loc) · 1.42 KB
/
KafkaService.js
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
const { Kafka } = require('kafkajs');
const moment = require('moment-timezone');
class KafkaService {
constructor() {
this.producer = null;
}
initService = async () => {
try {
const kafka = new Kafka({
clientId: process.env.KAFKA_CLIENT_ID,
brokers: [process.env.KAFKA_BROKER]
});
const producer = kafka.producer()
await producer.connect();
this.producer = producer;
console.log("Kafka Producer connected successfully.")
} catch (err) {
console.log(err);
}
}
getMomentDate = () => {
return moment().tz(process.env.TIME_ZONE).format("MM-DD HH:mm");
}
publishMessage = async (notificationType, topic, message, userId, orderId) => {
try {
const eventTime = this.getMomentDate(); // Use moment to format the date
const notification = {
notificationType,
eventTime: eventTime, // Now formatted "MM-DD HH:mm"
owner: userId,
message,
sourceID: orderId,
};
await this.producer.send({
topic: topic,
messages: [
{ value: JSON.stringify(notification) }
]
});
console.log(`Notification sent: ${JSON.stringify(notification)}`);
} catch (err) {
console.log(err);
}
}
closeService = async () => {
try {
await this.producer.disconnect();
} catch (err) {
console.log(err);
}
}
}
module.exports = {
KafkaService
};