-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
89 lines (74 loc) · 2.05 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* Distributed events library
*/
var uuid = require('uuid');
var util = require('util');
var EventEmitter = require('events');
var Emitter = function (pubClient, subClient) {
var _this = this;
EventEmitter.call(this);
this.uuid = uuid();
this.pubClient = pubClient;
this.subClient = subClient;
subClient.on('message', function (channel, msg) {
var count = _this.listenerCount(channel);
if (count) {
var args;
try {
args = JSON.parse(msg);
} catch (err) {
console.error('Parsing event message', err);
}
if (args[0] !== _this.uuid) {
args[0] = channel;
_this.emit.apply(_this, args);
}
}
});
}
util.inherits(Emitter, EventEmitter);
// KLUDGE, it is not possible to listen local and global for the same event in
// different parts of the code.
Emitter.prototype.on = function (evt, listener, isGlobal) {
var _this = this;
var args = Array.prototype.slice.call(arguments);
EventEmitter.prototype.on.apply(this, args);
if (isGlobal) {
return new Promise(function (resolve, reject) {
_this.subClient.subscribe(args[0], function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
})
}
return Promise.resolve(void 0);
}
Emitter.prototype.distEmit = function (evt) {
var _this = this;
var args = Array.prototype.slice.call(arguments);
this.emit.apply(this, args);
args[0] = this.uuid;
// Emit to other nodes
return new Promise(function (resolve, reject) {
_this.pubClient.publish(evt, JSON.stringify(args), function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
Emitter.prototype.off = Emitter.prototype.removeListener = function (evt, listener) {
var _this = this;
var args = Array.prototype.slice.call(arguments);
EventEmitter.prototype.removeListener.apply(this, args);
// TODO: we should take into consideration isGlobal.
if (!_this.listenerCount(evt)) {
_this.subClient.unsubscribe(evt);
}
}
module.exports = Emitter;