generated from homebridge/homebridge-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventsource.ts
63 lines (50 loc) · 1.47 KB
/
eventsource.ts
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
import { EventEmitter } from 'stream';
import { request, ClientRequest, IncomingMessage } from 'http';
import { URL } from 'url';
declare interface EventSource {
on(event: 'event', listener: (arg0: object) => void): this;
on(event: 'error', listener: (arg0: object | string) => void): this;
}
class EventSource extends EventEmitter {
private req: ClientRequest | undefined;
private readonly timeouts: Array<NodeJS.Timeout> = [];
constructor(private readonly url: URL) {
super();
}
close() {
this.removeAllListeners();
this.timeouts.forEach(timeout => {
clearTimeout(timeout);
});
if(this.req) {
this.req.removeAllListeners();
this.req.destroy();
}
}
connect() {
this.req = request(this.url, this.handleResponse.bind(this));
this.req.on('error', (err) => this.emit('error', err));
this.req.on('abort', () => this.emit('error', 'abort'));
this.req.on('close', this.handleClose.bind(this));
this.req.end();
}
private handleClose() {
if(this.req) {
this.req.removeAllListeners();
}
this.timeouts.push(setTimeout(this.connect.bind(this), 500));
}
private handleResponse(res: IncomingMessage) {
res.setEncoding('utf8');
res.on('data', this.handleData.bind(this));
}
private handleData(chunk: string) {
try {
const json = JSON.parse(chunk);
this.emit('event', json);
} catch (error) {
this.emit('error', error);
}
}
}
export default EventSource;