-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.js
53 lines (49 loc) · 1.27 KB
/
request.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
const stream = require("@weex-module/stream");
const native = require("@weex-module/test");
function request(options) {
let timeout;
let startTime = Date.now();
let requestOptions = {
method: options.method,
url: options.url
};
if (options.method === "POST") {
requestOptions.headers = {
"Content-Type": "application/json"
};
requestOptions.body = options.body;
}
if (options.headers) {
requestOptions.headers = options.headers;
}
return Promise.race([
new Promise((resolve, reject) => {
stream.fetch(requestOptions, ret => {
clearTimeout(timeout)
// 请求时间打点
native.reportInsightApiEvent(
`${options.method} ${options.url}`,
"timing",
String(Date.now() - startTime)
);
if (ret.ok) {
resolve(JSON.parse(ret.data));
} else {
reject(ret);
}
});
}),
new Promise((resolve, reject) => {
timeout = setTimeout(() => {
// 请求时间打点
native.reportInsightApiEvent(
`${options.method} ${options.url}`,
"timeout",
String(Date.now() - startTime)
);
reject("请求超时");
}, options.timeout || 5000);
})
]);
}
export default request;