-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch.ts
59 lines (51 loc) · 1.05 KB
/
fetch.ts
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
type Fetch = typeof fetch;
type Opts = Parameters<Fetch>[1];
export const post = async (url: string, body: any) => {
return f(url, {
method: 'post',
body: JSON.stringify(body)
});
};
export const del = async (url: string) => {
return f(url, {
method: 'delete'
});
};
export const get = async (url: string) => {
return f(url, {
method: 'get'
});
};
export const f = async (
url: string,
opts?: Opts,
client: Fetch = fetch
): Promise<[any, string | null, Response | null]> => {
let res: Response;
let data: any;
let _opts: Opts = {
headers: {
accept: 'application/json',
'Content-Type': 'application/json'
}
};
if (opts) {
_opts = { ..._opts, ...opts };
}
try {
res = await client(url, _opts);
data = await res.json();
} catch (err) {
return [null, err, null];
}
if (res.status >= 400) {
if (data && data.message) {
return [data, data.message, res];
} else if (typeof data === 'string') {
return [data, data, res];
} else {
return [data, 'Something went wrong.', res];
}
}
return [data, null, res];
};