-
Notifications
You must be signed in to change notification settings - Fork 0
/
emitter.js
45 lines (42 loc) · 1.15 KB
/
emitter.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
const EventEmitter = require('events').EventEmitter;
const emitterObj = {
emitter: new EventEmitter(),
connections: [],
emitFunc(ev, data) {
this.emitter.emit(ev, data);
},
addCon(res) {
res.req.ts = Date.now();
this.connections.push(res);
},
deleteCon(conID) {
if (this.connections.some(resE => resE.req.conID === conID)) {
this.connections.splice(
this.connections.findIndex(resE => resE.req.conID === conID),
1
);
}
},
cleanup() {
if (
this.connections.some(
resE => Date.now() - resE.req.ts > 24 * 60 * 60 * 1000
)
) {
this.connections = this.connections.filter(
resE => Date.now() - resE.req.ts < 24 * 60 * 60 * 1000
);
}
}
};
emitterObj.listenFunc = emitterObj.emitter.on('update', toStream => {
emitterObj.connections.map(resE => {
if (toStream.some(streamE => streamE.user === resE.req.user.id)) {
const data = toStream.find(streamE => streamE.user === resE.req.user.id);
resE.write('event: message\n');
resE.write(`data: ${JSON.stringify(data)}\n`);
resE.write('\n\n');
}
});
});
module.exports = emitterObj;