-
Notifications
You must be signed in to change notification settings - Fork 9
/
fetchAPI.ts
69 lines (59 loc) · 1.91 KB
/
fetchAPI.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
import type { APIPaths, APIRequests, APIResponse } from '../tests/openapiv31'
const baseURL = 'https://petstore3.swagger.io/api/v3'
export async function fetchAPI<
Path extends APIPaths,
Options extends APIRequests<Path>
> (path: Path, options?: Options): Promise<APIResponse<Path, Options['method']>> {
const fetchOptions: RequestInit = {
method: options?.method ?? 'get',
credentials: 'include',
headers: {
'Accept': 'application/json'
}
}
options = (options ?? {}) as Options
// Request body
const body = 'body' in options ? options['body'] : null
if (body && (
typeof body === 'string' ||
body instanceof FormData
)) {
fetchOptions.body = body
} else if (body) {
(fetchOptions.headers as Record<string, string>)['Content-Type'] = 'application/json'
fetchOptions.body = JSON.stringify(body)
}
// Replace url parameters (for instance "/path/{id}"
let urlPath: string = path
if ('urlParams' in options) {
for (const [name, value] of Object.entries(options.urlParams)) {
urlPath = urlPath.replace(`{${name}}`, value.toString())
}
}
const url = new URL(baseURL + urlPath);
// Add query parameters
if ('query' in options && options.query) {
for (const [name, value] of Object.entries(options.query)) {
url.searchParams.set(name, typeof value === 'object' ? JSON.stringify(value) : (value as any).toString())
}
}
const response = await fetch(url.toString(), fetchOptions)
if (!response.headers.get('content-type')?.includes('application/json')) {
throw new APIError({
message: await response.text()
}, response.status)
}
if (response.status === 204) {
return null as any
}
const data = await response.json()
if (response.ok) {
return data
}
throw new APIError(data, response.status)
}
export class APIError extends Error {
constructor (public data: object, public status: number) {
super()
}
}