-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrabbitmq.js
More file actions
99 lines (80 loc) · 2.9 KB
/
rabbitmq.js
File metadata and controls
99 lines (80 loc) · 2.9 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const amqp = require('amqplib/callback_api');
// docker RUN
// docker run -d -hostname rmq --name rabbitserver -p8080:15672 -p5672:5672 rabbitmq:3.12-managaement
class RabbitMq {
constructor(queue, queueOptions) {
this.queue = queue;
this.options = queueOptions;
this.channel = null;
// console.log(queueOptions)
this.connect()
.then((channel) => {
this.channel = channel;
})
.catch((error) => {
console.error('Error connecting to RabbitMQ:', error);
});
}
consumeCallback;
connection;
connect = () => {
return new Promise((resolve, reject) => {
amqp.connect(`${this.options.server}`, (error0, connection) => {
if (error0) {
return reject(error0);
}
this.connection = connection;
this.connection.createChannel((error1, channel) => {
if (error1) {
return reject(error1);
}
channel.assertQueue(this.queue, {
durable: false,
});
// Set the prefetch value to 1 to process messages one at a time
channel.prefetch(1);
this.channel = channel;
if (this.consumeCallback) {
this.channel.consume(this.queue, async (msg) => {
let data = JSON.parse(msg.content.toString());
await this.consumeCallback(data, (error)=>{
if(!error){
this.channel.ack(msg);
} else {
this.channel.nack(msg);
}
});
// Send acknowledgment (ack) after processing
});
}
resolve(channel);
});
});
});
};
process = async (callback) => {
this.consumeCallback = callback;
};
done() {
// console.log('done with a queue item');
}
sendToQueue = (queue, message, procedure, isEvent) => {
const finalMessage = {
data: message,
srcPath: this.queue,
path: procedure,
isEvent
}
this.channel.sendToQueue(queue, Buffer.from(JSON.stringify(finalMessage)));
// console.log('Message sent to queue:', message, 'queue:', queue);
}
add = (data) => {
if (!this.channel) {
throw new Error('Channel is not initialized. Call connect first.');
}
this.channel.sendToQueue(this.queue, Buffer.from(JSON.stringify(data)));
};
}
module.exports = {
RabbitMq
};