-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
49 lines (44 loc) · 1.45 KB
/
Copy pathindex.ts
File metadata and controls
49 lines (44 loc) · 1.45 KB
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
type ResponseFormat = 'json' | 'text' | 'response';
function _fetch(
url: string,
{ responseAs = 'json', ...opts }: RequestInit & { responseAs?: ResponseFormat } = {},
data?: {},
queryParams?: {},
): Promise<any> {
opts.headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
...opts.headers,
};
if (queryParams) {
url += `?${new URLSearchParams(queryParams)}`;
}
if (data !== undefined) {
opts.body = JSON.stringify(data);
} else {
delete opts.body;
}
return fetch(url, opts).then(response => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
if (responseAs === 'response') {
return response;
}
if (response.status === 204) {
return null;
}
return response[responseAs]();
});
}
export default function esfetch(url: string, opts = {}) {
const _ = (url_addition: string, opts_addition = {}) =>
esfetch(url + '/' + url_addition, { ...opts, ...opts_addition });
_.get = (queryParams?: { [key: string]: unknown } | [string, unknown][]) =>
_fetch(url, { ...opts, method: 'GET' }, undefined, queryParams);
_.post = (data?: any) => _fetch(url, { ...opts, method: 'POST' }, data);
_.put = (data?: any) => _fetch(url, { ...opts, method: 'PUT' }, data);
_.patch = (data?: any) => _fetch(url, { ...opts, method: 'PATCH' }, data);
_.delete = () => _fetch(url, { ...opts, method: 'DELETE' });
return _;
}