-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.js
45 lines (37 loc) · 1.15 KB
/
listener.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
const EventSource = require('eventsource');
const logger = require('./logger')("Listener");
class Listener {
constructor({protocol, hostname, port, path}) {
this.protocol = protocol;
this.hostname = hostname;
this.port = parseInt(port);
this.path = path.startsWith('/') ? path : '/' + path;
}
listen(cb) {
const url = this._url();
logger.info("Listening to stream on", url);
const es = new EventSource(url); // TODO we can do this ourselves
es.onmessage = e => logger.info("es message", e);
es.onerror = e => logger.error("es error", e);
es.addEventListener("EVENT", e => this._onEvent(e, cb));
}
_onEvent(e, cb) {
logger.info("EVENT", e);
cb(JSON.parse(e.data));
}
_url() {
let port;
if (this.protocol === 'https' && this.port === 443) {
port = '';
} else if (this.protocol === 'http' && this.port === 80) {
port = '';
} else {
port = ':' + this.port;
}
return `${this.protocol}://${this.hostname}${port}${this.path}`;
}
}
module.exports = (...args) => new Listener(...args);
if (require.main === module) {
throw Error('this script doesn\'t run standalone');
}