-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc.js
66 lines (53 loc) · 1.5 KB
/
rpc.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
export default class Rpc {
callbackId = 0
callbacks = new Map
constructor () {}
postCall (method, data, tx) {
this.port.postMessage({ call: method, ...data }, tx)
}
rpc (method, data, tx) {
return new Promise((resolve, reject) => {
const id = this.callbackId++
this.callbacks.set(id, data => {
this.callbacks.delete(id)
if (data.error) reject(data.error)
else resolve(data)
})
this.postCall(method, { data, callback: id }, tx)
})
}
callback (data) {
this.callbacks.get(data.responseCallback)(data.data ?? data)
}
register (port) {
this.port = port
this.port.addEventListener('message', async ({ data }) => {
// console.log(data)
if (!(data.call in this)) {
throw new ReferenceError(data.call + ' is not a method')
}
let result
try {
if (data.call === 'callback') {
result = await this[data.call](data)
} else {
result = await this[data.call](data.data ?? data)
}
} catch (error) {
result = { error }
}
if ('callback' in data) {
this.postCall('callback', { data: result, responseCallback: data.callback })
}
})
this.port.addEventListener('error', error => {
console.error(error)
this.postCall('onerror', { error })
})
this.port.addEventListener('messageerror', error => {
console.error(error)
this.postCall('onmessageerror', { error })
})
return this
}
}