-
Notifications
You must be signed in to change notification settings - Fork 5
/
mq_utils.js
86 lines (77 loc) · 2.27 KB
/
mq_utils.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
var amqp = require('amqplib');
var devUrl = 'amqp://localhost'
if (process.env.IN_DOCKER) {
devUrl = 'amqp://rabbitmq'
}
var amqUrl = process.env.AMQ_URL || devUrl;
var connection = null
var channel = null
var MESSAGES = []
function start() {
return new Promise(function (resolve, reject) {
amqp.connect(amqUrl).then(con => {
connection = con
console.log("AMQP Connection Opened!")
con.createChannel().then(chan => {
channel = chan;
channel.assertQueue("jobs");
channel.assertQueue("messages");
resolve(con)
});
}
)
});
}
async function publishToQueue(message) {
try {
console.log(connection)
channel.sendToQueue("jobs", Buffer.from(JSON.stringify(message)))
console.log(`Job sent successfully ${JSON.stringify(message)}`);
}
catch (ex) {
console.error(ex)
}
}
async function listenOnQueue(callbackFunc) {
try {
channel.consume("jobs", message => {
const input = JSON.parse(message.content.toString());
callbackFunc(input)
channel.ack(message);
})
console.log("Waiting for messages on jobs...")
}
catch (ex) {
console.error(ex)
}
}
async function listenOnMessagesQueue() {
try {
channel.consume("messages", message => {
const input = JSON.parse(message.content.toString());
console.log("Message Recieved! " + message.content.toString())
input.sent_time = parseInt(input.sent_time)
MESSAGES.push(input)
channel.ack(message);
})
console.log("Waiting for messages on messages...")
}
catch (ex) {
console.error(ex)
}
}
async function publishMessageToQueue(message) {
try {
channel.sendToQueue("messages", Buffer.from(JSON.stringify(message)))
console.log(`Message sent successfully ${JSON.stringify(message)}`);
}
catch (ex) {
console.error(ex)
}
}
exports.publishToQueue = publishToQueue;
exports.publishMessageToQueue = publishMessageToQueue;
exports.listenOnMessagesQueue = listenOnMessagesQueue;
exports.listenOnQueue = listenOnQueue;
exports.start = start;
exports.MESSAGES = MESSAGES;