-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateBaseFetcher.ts
More file actions
45 lines (36 loc) · 1.21 KB
/
Copy pathcreateBaseFetcher.ts
File metadata and controls
45 lines (36 loc) · 1.21 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
import type { z } from 'zod'
import ApiError from '@/utils/ApiError'
interface Props<T extends z.ZodType> {
getToken: () => Promise<string>
baseURL: string
schema: T
}
interface ErrorBody {
error?: string
message?: string
}
const isErrorBody = (value: unknown): value is ErrorBody =>
typeof value === 'object' && value !== null
const createBaseFetcher =
<T extends z.ZodType>({ getToken, baseURL, schema }: Props<T>) =>
async (path: string, init?: RequestInit): Promise<z.infer<T>> => {
const token = await getToken()
const response = await fetch(`${baseURL}${path}`, {
...init,
headers: {
...init?.headers,
Authorization: `Bearer ${token}`,
},
})
if (!response.ok) {
const body: unknown = await response.json().catch(() => null)
const statusText = (isErrorBody(body) && body.error) || response.statusText || 'Error'
const message = (isErrorBody(body) && body.message) || response.statusText || 'Request failed'
throw new ApiError(response.status, statusText, message)
}
if (response.status === 204) {
return schema.parse(undefined)
}
return schema.parse(await response.json())
}
export default createBaseFetcher