1 | function getResponseHeaders(headers) {
|
2 | const d = {};
|
3 | headers.forEach(([k, v]) => {
|
4 | d[k] = v;
|
5 | });
|
6 | return d;
|
7 | }
|
8 | function fetchAs(fetchType) {
|
9 | return async (url, options) => {
|
10 | let status = -1;
|
11 | let headers = {};
|
12 | let size = -1;
|
13 | let timeout = -1;
|
14 | let type = 'basic';
|
15 | try {
|
16 | const r = await fetch(url, options);
|
17 | const d = await r[fetchType]();
|
18 | status = r.status;
|
19 | headers = getResponseHeaders(r.headers);
|
20 | size = r.size || -1;
|
21 | timeout = r.timeout || -1;
|
22 | type = r.type;
|
23 | return {
|
24 | status,
|
25 | info: { headers, size, timeout, type },
|
26 | [status > 399 ? 'error' : 'data']: d,
|
27 | };
|
28 | }
|
29 | catch (e) {
|
30 | return {
|
31 | status,
|
32 | info: { headers, size, timeout, type },
|
33 | error: e,
|
34 | };
|
35 | }
|
36 | };
|
37 | }
|
38 | export async function fetchAsArrayBuffer(url, options) {
|
39 | return fetchAs('arrayBuffer')(url, options);
|
40 | }
|
41 | export async function fetchAsBlob(url, options) {
|
42 | return fetchAs('blob')(url, options);
|
43 | }
|
44 | export async function fetchAsJson(url, options) {
|
45 | return fetchAs('json')(url, options);
|
46 | }
|
47 | export async function fetchAsText(url, options) {
|
48 | return fetchAs('text')(url, options);
|
49 | }
|
50 | export default {
|
51 | arrayBuffer: fetchAsArrayBuffer,
|
52 | blob: fetchAsBlob,
|
53 | json: fetchAsJson,
|
54 | text: fetchAsText,
|
55 | };
|
56 |
|
\ | No newline at end of file |