File size: 1,425 Bytes
0573fbf
 
 
 
 
 
 
9426218
 
0573fbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
async function request(method, url, body, config = {}) {
    const init = { method };
    const headers = { ...(config.headers || {}) };

    if (body !== undefined && body !== null) {
        if (body instanceof FormData) {
            init.body = body;
            // Let the browser set Content-Type so the multipart boundary is included.
            delete headers['Content-Type'];
        } else {
            init.body = JSON.stringify(body);
            if (!headers['Content-Type']) headers['Content-Type'] = 'application/json';
        }
    }
    if (Object.keys(headers).length > 0) init.headers = headers;

    const response = await fetch(url, init);

    let data;
    if (config.responseType === 'blob') {
        data = await response.blob();
    } else {
        const text = await response.text();
        try { data = text ? JSON.parse(text) : null; }
        catch { data = text; }
    }

    if (!response.ok) {
        const err = new Error(`HTTP ${response.status}`);
        err.response = { status: response.status, data };
        throw err;
    }
    return { data, status: response.status };
}

const api = {
    get: (url, config) => request('GET', url, null, config),
    post: (url, body, config) => request('POST', url, body, config),
    put: (url, body, config) => request('PUT', url, body, config),
    delete: (url, config) => request('DELETE', url, null, config),
};

export default api;