-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
72 lines (62 loc) · 1.74 KB
/
worker.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
const amqp = require('amqp-connection-manager')
const {main} = require('./app.js');
const AMQP_URL = process.env.CLOUDAMQP_URL || 'amqp://localhost';
if (!AMQP_URL) process.exit(1)
// GLOBALES
const WORKER_QUEUE = 'worker-queue'
// RABBITMQ
// Create a new connection manager from AMQP
var connection = amqp.connect([AMQP_URL])
console.log('[AMQP] - Connecting....')
connection.on('connect', function() {
process.once('SIGINT', function() { // Close conn on exit
connection.close()
})
return console.log('[AMQP] - Connected!')
})
connection.on('disconnect', function(params) {
return console.error('[AMQP] - Disconnected.', params.err.stack)
})
// To receive the execution task messages
let channelWrapper = connection.createChannel({
json: true,
setup: function(channel) {
return Promise.all([
channel.assertQueue(WORKER_QUEUE, { autoDelete: false, durable: true }),
channel.prefetch(1),
channel.consume(WORKER_QUEUE, onMessage)
])
}
})
channelWrapper.waitForConnect()
.then(function() {
console.log('[AMQP] - Listening for messages on queue => '+WORKER_QUEUE)
})
.catch(function(err) {
console.error('[AMQP] - Error! ', err)
})
// Process message from AMQP
function onMessage(data) {
let message
try {
message = JSON.parse(data.content.toString())
} catch(e) {
console.error('[AMQP] - Error parsing message... ', data)
}
console.log('[AMQP] - Message incoming... ', message)
channelWrapper.ack(data)
if (!message) {
return
}
// Actions here
switch (message.taskName) {
case 'getNotes':
main();
break
// case 'other':
// // do another thing....
// break
default:
console.error('No task was found with name => '+message.taskName)
}
}