-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
61 lines (56 loc) · 1.54 KB
/
Copy pathindex.ts
File metadata and controls
61 lines (56 loc) · 1.54 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
50
51
52
53
54
55
56
57
58
59
60
61
export type TDefinedRecords<TTypes = any> = Record<
keyof TTypes,
TTypes[keyof TTypes]
>
export type IRequestParams<TParamTypes = any, TBodyTypes = any> = {
params?: TDefinedRecords<TParamTypes>
body?: RequestInit['body'] | TDefinedRecords<TBodyTypes>
}
export type TRequestMethods = 'get' | 'post' | 'put' | 'delete'
export default function buildFetcher<THeaders>({
baseUrl,
headers,
}: {
baseUrl?: string
headers?:
| Headers
| TDefinedRecords<THeaders>
| (() => TDefinedRecords<THeaders>)
}) {
return new Proxy(
{} as {
[key in TRequestMethods]: <T = any>(
path: string,
options?: RequestInit & IRequestParams
) => Promise<T>
},
{
get:
(_, method) =>
async (path: string, options: RequestInit & IRequestParams = {}) => {
const url = new URL(`${baseUrl}${path}`)
if (options.params) {
Object.entries(options.params).forEach(([key, value]) => {
url.searchParams.append(key, value)
})
}
if (
method === 'post' &&
options.body &&
typeof options.body === 'object'
) {
options.body = JSON.stringify(options.body)
}
const response = await fetch(url, {
headers: {
...(typeof headers === 'function' ? headers() : headers),
...options.headers,
},
...options,
method: method as string,
})
return response.json()
},
}
)
}