-
Notifications
You must be signed in to change notification settings - Fork 3
/
fetcher.ts
48 lines (40 loc) · 1.23 KB
/
fetcher.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
export interface FetcherOptions<TQueryParams = never, TBody = never, THeaderParams = HeadersInit>
extends Omit<RequestInit, 'body' | 'headers'> {
url: string;
queryParams?: TQueryParams extends never ? undefined : TQueryParams;
body?: TBody extends never ? undefined : TBody;
headers?: THeaderParams;
}
const JSON_HEADERS = ['application/json'];
interface ResponseContainer<TResponse, TResponseHeaders> {
body: TResponse;
headers: TResponseHeaders;
}
export async function fetcher<
TResponse = unknown,
TQueryParams = never,
TBody = never,
THeaderParams = HeadersInit,
>(
options: FetcherOptions<TQueryParams, TBody, THeaderParams>,
): Promise<ResponseContainer<TResponse, Headers>> {
const { body, url, queryParams, headers, ...rest } = options;
const response = await fetch(url, {
body: body ? JSON.stringify(body) : undefined,
headers: {
'Content-Type': JSON_HEADERS[0],
...(headers as HeadersInit),
},
...rest,
});
const contentType = response.headers.get('Content-Type');
const asJson = contentType && JSON_HEADERS.some((h) => contentType.startsWith(h));
const data = await (asJson ? response.json() : response.text());
if (response.ok) {
return {
body: data,
headers: response.headers,
};
}
throw data;
}