-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
116 lines (112 loc) · 2.55 KB
/
utils.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
const WebSocket = require("ws");
const fetch = require("node-fetch");
let id = 0;
let id2 = 0;
function requestWs({ url, id, method, params }) {
let startTime;
let endTime;
return new Promise((resolve, reject) => {
const message = JSON.stringify({ id, jsonrpc: "2.0", method, params });
const ws = new WebSocket(url);
ws.onmessage = m => {
try {
const data = JSON.parse(m.data);
if (data.id === id) {
endTime = Date.now();
resolve({
data: data.result,
wastTime: endTime - startTime
});
ws.close();
}
} catch (err) {
reject(err);
}
};
ws.onopen = () => {
startTime = Date.now();
ws.send(message);
};
ws.onerror = err => {
ws.close();
reject(err);
};
});
}
const fetchFromWs = ({ url, method, params = [], timeOut = 5000 }) => {
id = id + 1;
if (timeOut) {
return Promise.race([
requestWs({ url, method, params, id }),
new Promise((resovle, reject) => {
setTimeout(() => {
reject("请求超时");
}, timeOut);
})
]);
} else {
return requestWs({ url, method, params, id });
}
};
const fetchFromHttp = ({
url,
method = "POST",
methodAlias,
params = [],
body,
timeOut = 5000,
header = {}
}) => {
id2 = id2 + 1;
const message = body
? JSON.stringify(body)
: JSON.stringify({ id, jsonrpc: "2.0", method: methodAlias, params });
const request = () =>
fetch(url, {
method: method,
headers: {
method,
Accept: "application/json",
"Content-Type": "application/json",
...header
},
...(method.toUpperCase() === "GET" ? {} : { body: message })
})
.then(async res => {
try {
if (res && res.status >= 200 && res.status < 300) {
return res.json();
} else {
const result = await res.json();
return Promise.reject({
status: res.status,
message: result
});
}
} catch (e) {
return Promise.reject({
status: res.status,
message: e.message
});
}
})
.catch(err => {
return Promise.reject(err);
});
if (timeOut) {
return Promise.race([
request(),
new Promise((resovle, reject) => {
setTimeout(() => {
reject("请求超时");
}, timeOut);
})
]);
} else {
return request();
}
};
module.exports = {
fetchFromWs,
fetchFromHttp
};