-
Notifications
You must be signed in to change notification settings - Fork 2
/
rabbit.js
48 lines (38 loc) · 968 Bytes
/
rabbit.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
let rabbit = undefined;
let channel = undefined;
async function getConnection() {
if (channel !== undefined) {
return channel;
}
if (rabbit === undefined) {
rabbit = await require('amqplib').connect(APP_REDDITMQ_HOST);
}
if (channel === undefined) {
channel = await rabbit.createChannel();
channel.prefetch(1);
}
return channel;
}
async function consume(queue) {
const channel = await getConnection();
return channel.get(queue, {noAck: true});
}
async function ack(message) {
const channel = await getConnection();
return channel.ack(message)
}
async function store(queue, message) {
const channel = await getConnection();
return channel.sendToQueue(queue, Buffer.from(typeof message !== 'string' ? JSON.stringify(message) : message))
}
export default {
consume,
store,
ack
};
process.on("exit", (code) => {
if (channel !== undefined) {
channel.close();
console.log("Closing rabbit channel!")
}
})