-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
65 lines (57 loc) · 1.29 KB
/
index.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
'use strict';
const
bole = require('bole'),
Squeaky = require('squeaky'),
url = require('url')
;
module.exports = createRelayer;
function createRelayer(opts = {})
{
return new NSQRelayer(opts);
}
class NSQRelayer
{
constructor({ nsq = 'http://127.0.0.1:4151', topic = 'relayed', event = 'nsq', relays = null })
{
const parsed = url.parse(nsq);
this.dest = nsq;
this.nsq = new Squeaky({ host: parsed.hostname, port: parsed.port || 4150 });
this.logger = bole('nsq-relay');
this.events = {};
if (Array.isArray(relays) && relays.length > 0)
{
relays.forEach(topic =>
{
const fn = msg => this.handleEvent(topic, msg);
process.on(topic, fn);
this.events[topic] = fn;
});
}
else
{
const fn = msg => this.handleEvent(topic, msg);
process.on(event, fn);
this.events[event] = fn;
}
}
handleEvent(topic, message)
{
this.nsq.publish(topic, message).then(resp =>
{
// silence on success
this.logger.debug(resp, message);
}).catch(err =>
{
this.logger.warn(`error ${err.message} posting to ${topic} at ${this.dest}; dropping message on the floor `);
});
}
close()
{
Object.keys(this.events).forEach(evt =>
{
process.removeListener(evt, this.events[evt]);
});
this.nsq.close();
}
}
createRelayer.NSQRelayer = NSQRelayer;