| 16 | } |
| 17 | |
| 18 | private async request<T>(endpoint: string, options: RequestOptions = {}): Promise<T> { |
| 19 | const { params, ...init } = options |
| 20 | |
| 21 | let url = `${this.baseUrl}${endpoint}` |
| 22 | if (params) { |
| 23 | const searchParams = new URLSearchParams(params) |
| 24 | url += `?${searchParams.toString()}` |
| 25 | } |
| 26 | |
| 27 | const headers: Record<string, string> = { ...init.headers as Record<string, string> } |
| 28 | // 只有在有 body 时才设置 Content-Type |
| 29 | if (init.body !== undefined) { |
| 30 | headers['Content-Type'] = 'application/json' |
| 31 | } |
| 32 | const response = await fetch(url, { |
| 33 | ...init, |
| 34 | headers, |
| 35 | credentials: init.credentials ?? 'same-origin', |
| 36 | }) |
| 37 | |
| 38 | if (!response.ok) { |
| 39 | const error = await response.json().catch(() => ({})) as ApiErrorPayload |
| 40 | throw new ApiError( |
| 41 | response.status, |
| 42 | typeof error.message === 'string' |
| 43 | ? error.message |
| 44 | : typeof error.error === 'string' |
| 45 | ? error.error |
| 46 | : 'Request failed', |
| 47 | error, |
| 48 | ) |
| 49 | } |
| 50 | |
| 51 | if (response.status === 204) { |
| 52 | return undefined as T |
| 53 | } |
| 54 | |
| 55 | return response.json() |
| 56 | } |
| 57 | |
| 58 | get<T>(endpoint: string, options?: RequestOptions) { |
| 59 | return this.request<T>(endpoint, { ...options, method: 'GET' }) |