forked from axetroy/wxapp-fetch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (57 loc) · 1.54 KB
/
index.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
// @flow
import http from 'wxapp-http';
const httpClient = http.create({
maxConcurrent: 10,
timeout: 0,
header: {},
dataType: 'json'
});
function generateResponse(res) {
let header = res.header || {};
let config = res.config || {};
return {
ok: ((res.statusCode / 200) | 0) === 1, // 200-299
status: res.statusCode,
statusText: res.errMsg,
url: config.url,
clone: () => generateResponse(res),
text: () =>
Promise.resolve(
typeof res.data === 'string' ? res.data : JSON.stringify(res.data)
),
json: () => {
if (typeof res.data === 'object') return Promise.resolve(res.data);
let json = {};
try {
json = JSON.parse(res.data);
} catch (err) {
console.error(err);
}
return json;
},
blob: () => Promise.resolve(new Blob([res.data])),
headers: {
keys: () => Object.keys(header),
entries: () => {
let all = [];
for (let key in header) {
if (header.hasOwnProperty(key)) {
all.push([key, header[key]]);
}
}
return all;
},
get: n => header[n.toLowerCase()],
has: n => n.toLowerCase() in header
}
};
}
export default (typeof fetch === 'function'
? fetch.bind()
: function(url, options) {
options = options || {};
return httpClient
.request(options.method || 'get', url, options.body, options.headers)
.then(res => Promise.resolve(generateResponse(res)))
.catch(res => Promise.reject(generateResponse(res)));
});