-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
68 lines (54 loc) · 1.94 KB
/
client.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
66
67
68
let ws,
reconnector,
eventTarget = document.createElement("div");
const generateID = () =>
`_${
Number(String(Math.random()).slice(2)) +
Date.now() +
Math.round(performance.now()).toString(36)
}`;
const AsyncAwaitWebsocket = (url, options) => {
const { reconnectInterval } = options || { reconnectInterval: 1000 };
ws = new WebSocket(url, generateID());
ws.sid = ws.protocol;
ws.sendSync = (event, data) => ws.send(JSON.stringify([event, data]));
ws.sendAsync = (event, data, timeout = 3000) =>
new Promise((resolve, reject) => {
const trigger = ({ detail }) => {
clearTimeout(id);
eventTarget.removeEventListener(event, trigger);
detail?.error ? reject(detail) : resolve(detail);
};
const id = setTimeout(() => {
eventTarget.removeEventListener(event, trigger);
reject({ error: "WebSocket error (client): request timed out" });
}, timeout);
ws.send(JSON.stringify([event, data]));
eventTarget.addEventListener(event, trigger);
});
ws.on = (event, callback) => {
const cb = ({ detail }) => callback(detail);
eventTarget.addEventListener(event, cb);
ws.off = (event) => eventTarget.removeEventListener(event, cb);
};
ws.addEventListener("open", (detail) => {
clearTimeout(reconnector);
eventTarget.dispatchEvent(new CustomEvent("open", { detail }));
});
ws.addEventListener("close", (detail) => {
reconnector = setTimeout(
AsyncAwaitWebsocket.bind(undefined, url, options),
reconnectInterval
);
eventTarget.dispatchEvent(new CustomEvent("close", { detail }));
});
ws.addEventListener("error", (detail) =>
eventTarget.dispatchEvent(new CustomEvent("error", { detail }))
);
ws.addEventListener("message", ({ data }) => {
const [event, detail] = JSON.parse(data);
eventTarget.dispatchEvent(new CustomEvent(event, { detail }));
});
return ws;
};
export default AsyncAwaitWebsocket;