-
Notifications
You must be signed in to change notification settings - Fork 0
/
messages.js
80 lines (45 loc) · 1.54 KB
/
messages.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
"use strict";
const got = require('got');
// Send message via http
class HTTPMessage {
send(url, body) {
return new Promise((resolve, reject) => {
got.post(url, { json: body }, function(error, response, data) {
if (!error && response.statusCode == 200) {
console.log(JSON.stringify(response.body));
resolve(response.body);
} else {
console.log("Error sending message to HTTP endpoint: " + url + ". Response body: " + JSON.stringify(response.body) + ". Error: " + error + ". Sent body: " + JSON.stringify(body) + ".");
resolve(error);
}
});
});
}
}
// Send message via message queue
class QueueMessage {
constructor(connection, queue) {
this.connection = connection;
this.queue = queue;
}
send(url, body) {
let queue = this.queue;
return this.connection.createChannel().then(function(channel) {
var ok = channel.assertQueue(queue);
return ok.then(function(queueOK) {
var response = channel.sendToQueue(queue, Buffer.from(JSON.stringify(body)));
if ( !response ) {
console.log("Not ready to send yet.");
// Handle queue that is not ready for new messages yet: https://github.com/squaremo/amqp.node/issues/61
channel.once('drain', function() {
console.log("Ready!");
return channel.close();
});
} else {
return channel.close();
}
});
});
}
}
module.exports = { HTTPMessage, QueueMessage };