-
Notifications
You must be signed in to change notification settings - Fork 375
/
index.js
63 lines (51 loc) · 1.33 KB
/
index.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
"use strict";
const { EventEmitter } = require("@xmpp/events");
class Reconnect extends EventEmitter {
constructor(entity) {
super();
this.delay = 1000;
this.entity = entity;
this._timeout = null;
}
scheduleReconnect() {
const { entity, delay, _timeout } = this;
clearTimeout(_timeout);
this._timeout = setTimeout(async () => {
if (entity.status !== "disconnect") {
return;
}
try {
await this.reconnect();
} catch {
// Ignoring the rejection is safe because the error is emitted on entity by #start
}
}, delay);
}
async reconnect() {
const { entity } = this;
this.emit("reconnecting");
const { service, domain, lang } = entity.options;
await entity.connect(service);
await entity.open({ domain, lang });
this.emit("reconnected");
}
start() {
const { entity } = this;
const listeners = {};
listeners.disconnect = () => {
this.scheduleReconnect();
};
this.listeners = listeners;
entity.on("disconnect", listeners.disconnect);
}
stop() {
const { entity, listeners, _timeout } = this;
entity.removeListener("disconnect", listeners.disconnect);
clearTimeout(_timeout);
}
}
module.exports = function reconnect({ entity }) {
const r = new Reconnect(entity);
r.start();
return r;
};