This repository has been archived by the owner on Mar 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.js
65 lines (55 loc) · 1.6 KB
/
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const EventEmitter = require('eventemitter3');
const emitter = new EventEmitter();
const fetch = require('node-fetch');
const HEARTBEAT_TIME = 15000;
function subscribe(req, res) {
console.log(`[${new Date().toLocaleString()}] New client connected from ${req.ip}`);
res.writeHead(
200,
{
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive'
}
);
// heartbeat
const nln = function() {
res.write('\n');
}
const heartbeat = setInterval(nln, HEARTBEAT_TIME);
const onEvent = function(data) {
res.write('retry: 3000\n');
res.write('event: message\n');
res.write(`id: ${new Date().getTime()}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
}
emitter.on('event', onEvent);
req.on(
'close',
function() {
clearInterval(heartbeat);
emitter.removeListener('event', onEvent);
}
);
// on connectino send open event:
res.write('event: open\n\n');
// on connection send example message:
onEvent({when: new Date(), message: `Hello! I'll keep sending you messages from server`});
// as this is a DEMO, send a Chuck Norris fact every 5 seconds:
setInterval(
() => {
fetch('https://api.chucknorris.io/jokes/random')
.then( (res) => res.json() )
.then( (data) => {onEvent({when: new Date(data.updated_at), message: data.value})} )
.catch( (error) => onEvent({when: new Date(), message: '[!!!] Error getting data from source!'}) );
},
5000
);
}
function publish(eventData) {
emitter.emit('event', eventData);
}
module.exports = {
subscribe,
publish
};