-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.js
133 lines (121 loc) · 2.92 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
const { nanoid } = require('nanoid')
const UNHANDLED_MESSAGE = 'unhandledMessage'
module.exports = class EspecialClient {
constructor(url, _WebSocket = WebSocket) {
this.url = url
this._ridListeners = {}
this.connected = false
this.reconnect = true
this.retries = Infinity
this.connectionHandlers = {}
this._WebSocket = _WebSocket
this.listeners = {
[UNHANDLED_MESSAGE]: [],
}
}
once(_rid, fn) {
this._ridListeners[_rid] = async (...args) => {
delete this._ridListeners[_rid]
fn(...args)
}
}
on(message, fn) {
if (!Array.isArray(this.listeners[message])) {
throw new Error(`Unrecognized event "${message}"`)
}
this.listeners[message].push(fn)
}
listen(_rid, fn) {
this._ridListeners[_rid] = fn
}
clearListener(_rid) {
delete this._ridListeners[_rid]
}
addConnectedHandler(fn) {
const id = nanoid()
this.connectionHandlers[id] = fn
return id
}
clearConnectedHandler(id) {
delete this.connectionHandlers[id]
}
async send(route, data = {}) {
if (!this.connected) {
throw new Error('Not connected')
}
const _rid = nanoid()
const p = new Promise((rs, rj) => {
this.once(_rid, (err, payload) => {
if (err) rj(err)
else rs(payload)
})
})
const payload = {
_rid,
route,
data,
}
this.ws.send(JSON.stringify(payload))
return await p
}
async connect(retryCount = 0) {
const ws = new this._WebSocket(this.url)
await new Promise((rs, rj) => {
ws.onmessage = ({ data }) => {
this._handleMessage(data)
}
ws.onopen = () => {
this.ws = ws
this.connected = true
rs()
for (const [key, fn] of Object.entries(this.connectionHandlers)) {
fn()
}
}
ws.onclose = async () => {
const newDisconnect = this.connected
this.connected = false
delete this.ws
if (newDisconnect) {
for (const [key, fn] of Object.entries(this.connectionHandlers)) {
fn()
}
}
}
ws.onerror = async (err) => {
ws.close()
if (!this.reconnect || retryCount >= this.retries) {
return rj(err)
}
rs()
await new Promise(r => setTimeout(r, 2000))
await this.connect(++retryCount)
}
})
}
disconnect() {
if (!this.connected) return
this.ws.close()
}
_handleMessage(data) {
const payload = JSON.parse(data)
const fn = this._ridListeners[payload._rid]
if (typeof fn !== 'function') {
const fns = this.listeners[UNHANDLED_MESSAGE]
if (fns.length === 0) {
console.error(payload)
console.error('No handler for message')
return
}
for (const _fn of fns) {
_fn()
}
return
}
if (payload.status === 0) {
fn(null, payload)
} else {
fn(payload)
}
}
}