-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch.js
57 lines (51 loc) · 1.48 KB
/
fetch.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
import queryString from 'query-string';
import { omitBy, startsWith, isUndefined } from 'lodash';
import config from '../config';
export default function handledFetch(path, options) {
return fetch(path, options)
.then((res) => {
if (res.status >= 400) {
const err = new Error('Bad response from server');
err.status = res.status;
const contentType = res.headers.get('content-type');
if (startsWith(contentType, 'application/json')) {
return res.json()
.then((content) => {
err.content = content;
throw err;
});
}
return res.text()
.then((content) => {
err.content = content;
throw err;
});
}
return res;
});
}
export function apiFetch(path, options = {}) {
let qs = '';
const isFormData = options.body instanceof FormData;
if (typeof options.body === 'object' && !isFormData) {
options.body = JSON.stringify(options.body);
}
if (options.query) {
const query = omitBy(options.query, isUndefined);
qs = `?${queryString.stringify(query)}`;
}
options = Object.assign({ credentials: 'include' }, options);
if (!isFormData) {
options.headers = {
'Content-Type': 'application/json',
...options.headers,
}
}
return handledFetch(`${config.API_URL}${path}${qs}`, options)
.then((res) => {
if (res.status === 200) {
return res.json();
}
return true;
});
}