-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrpc.js
More file actions
94 lines (91 loc) · 2.21 KB
/
Copy pathrpc.js
File metadata and controls
94 lines (91 loc) · 2.21 KB
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
const { WebSocket } = require('unws')
class RPC {
constructor(url) {
this.url = url
this.wsOptions = {
headers: {
"x-pinokio-client": "pterm"
}
}
}
async status(rpc) {
let res = await new Promise((resolve, reject) => {
this.run({
status: true,
...rpc
}, (stream) => {
resolve(stream.data)
this.ws.close()
})
})
return res
}
close() {
if (!this.ws) {
return
}
const ws = this.ws
delete this.ws
if (typeof ws.terminate === 'function') {
ws.terminate()
return
}
ws.close()
}
stop(rpc) {
this.run({
stop: true,
...rpc
})
}
run (rpc, ondata) {
// use fetch
/*
FormData := [
types_array: ['number', 'boolean']
]
body := {
}
*/
return new Promise((resolve, reject) => {
if (this.ws) {
this.ws.send(JSON.stringify(rpc))
} else {
const ws = new WebSocket(this.url, this.wsOptions)
this.ws = ws
ws.addEventListener('open', () => {
ws.send(JSON.stringify(rpc))
});
ws.addEventListener('message', (message) => {
/******************************************************************************
******************************************************************************/
if (ondata) {
const rawMessage = message && typeof message === 'object' && typeof message.data !== 'undefined'
? message.data
: message
const packetSource = Buffer.isBuffer(rawMessage)
? rawMessage.toString('utf8')
: String(rawMessage)
const packet = JSON.parse(packetSource);
ondata(packet)
}
});
ws.addEventListener('close', () => {
// console.log('Disconnected from WebSocket endpoint', { error: this.error, result: this.result });
if (this.ws === ws) {
delete this.ws
}
resolve()
});
}
})
}
respond(response) {
if (this.ws) {
this.ws.send(JSON.stringify(response))
} else {
throw new Error("socket not connected")
}
}
}
module.exports = RPC