-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.ts
75 lines (60 loc) · 1.74 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import QueryString from 'qs';
const TIME_OUT = 30000;
export class FetchError extends Error {
constructor(public status: number, message: string) {
super(message);
this.name = 'FetchError';
}
}
export type Method = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
export interface FetchApiRequest<K = unknown> {
url: string;
params?: K;
method?: Method;
body?: unknown;
timeout?: number;
config?: Omit<RequestInit, 'method' | 'body'>;
}
export const paramsSerializer = <T>(params: T): string => QueryString.stringify(params, {
arrayFormat: 'comma',
indices: false,
});
async function fetchApi<T, K = unknown>({
url,
params,
body,
config = {},
timeout = TIME_OUT,
method = 'GET',
}: FetchApiRequest<K>): Promise<T> {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(`${url}${params ? `?${paramsSerializer(params)}` : ''}`, {
...config,
body: body ? JSON.stringify(body) : undefined,
method,
signal: controller.signal,
headers: body ? {
'Content-Type': 'application/json',
...config.headers,
} : config.headers,
});
clearTimeout(id);
if (!response.ok) {
const errorBody = await response.json().catch(() => ({}));
throw new FetchError(response.status, errorBody?.message || response.statusText);
}
const data = await response.json() as T;
return data;
} catch (error) {
if (error instanceof FetchError) {
throw error;
}
if (error instanceof Error && error.name === 'AbortError') {
throw new FetchError(408, 'Request Timeout');
}
throw new FetchError(500, 'Internal Server Error');
}
}
export default fetchApi;