forked from mdmuhtasimfuadfahim/kafka-pub-sub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConsumeEvent.js
60 lines (53 loc) · 2.17 KB
/
ConsumeEvent.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
const kafka = require('./config/kafka');
const config = require('./config/config');
const validateTopic = require('./validation/validateTopic');
const validateEvent = require('./validation/validateEvent');
const validateData = require('./validation/validateData');
const validateHeaders = require('./validation/validateHeaders');
const consumer = kafka.consumer({ groupId: config.kafka_group_id });
/**
* An asynchronous function that consumes events from a specified topic.
* It validates the topic, each message's event and data before returning the message data object.
*
* @param {string} topic - The topic to consume events from.
* @return {Promise<object>} The message data object containing topic, partition, offset, timestamp, key, value, and headers.
*/
const ConsumeEvent = async (topic) => {
await consumer.connect();
await consumer.subscribe({ topics: [topic], fromBeginning: true });
validateTopic(topic);
return new Promise(async (resolve, reject) => {
try {
await consumer.run({
eachMessage: async ({ topic, partition, message, heartbeat }) => {
let key = message.key.toString();
validateEvent(message.key.toString());
let value = JSON.parse(message.value);
validateData(value);
let headers = Object.keys(message.headers).reduce(
(headers, key) => ({
...headers,
[key]: message.headers[key].toString(),
}),
{}
);
validateHeaders(headers);
const data = {
topic,
partition,
offset: message.offset,
timestamp: message.timestamp,
key,
value,
headers,
};
await heartbeat();
resolve(data);
},
})
} catch (error) {
reject(error.message);
}
});
}
module.exports = ConsumeEvent;