-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.js
43 lines (35 loc) · 991 Bytes
/
events.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
const EventEmitter = require('eventemitter3');
const emitter = new EventEmitter();
function subscribe(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive'
});
// Heartbeat
res.write('\n');
const nln = function() {
res.write('\n');
};
const hbt = setInterval(nln, 15000);
const onEvent = function(data) {
res.write('retry: 500\n');
res.write(`event: event\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
emitter.on('event', onEvent);
// Clear heartbeat and listener
req.on('close', function() {
clearInterval(hbt);
emitter.removeListener('event', onEvent);
});
}
function publish(req, res) {
// Emit events here recieved from Github/Twitter APIs
emitter.emit('event', req.body);
res.status(200).send();
}
module.exports = {
subscribe, // Sending event data to the clients
publish // Emiting events from streaming servers
};