(
path: string,
init: Omit<RequestInit, "headers"> & { headers?: Record<string, string> } = {},
)
| 25 | } |
| 26 | |
| 27 | export async function api<T>( |
| 28 | path: string, |
| 29 | init: Omit<RequestInit, "headers"> & { headers?: Record<string, string> } = {}, |
| 30 | ): Promise<T> { |
| 31 | let res: Response; |
| 32 | try { |
| 33 | res = await fetch(path, { |
| 34 | credentials: "include", |
| 35 | ...init, |
| 36 | headers: { |
| 37 | ...(typeof init.body === "string" ? { "content-type": "application/json" } : {}), |
| 38 | ...init.headers, |
| 39 | }, |
| 40 | }); |
| 41 | } catch { |
| 42 | throw new ApiError(0, "network", "network error"); |
| 43 | } |
| 44 | if (res.status === 204) return undefined as T; |
| 45 | if (!res.ok) { |
| 46 | const retryAfterRaw = Number(res.headers.get("retry-after")); |
| 47 | const retryAfter = Number.isFinite(retryAfterRaw) && retryAfterRaw > 0 ? retryAfterRaw : undefined; |
| 48 | let type: ApiErrorType = "internal"; |
| 49 | let message = res.statusText || `HTTP ${res.status}`; |
| 50 | try { |
| 51 | const body = (await res.json()) as ErrorBody; |
| 52 | if (body.error?.type) type = body.error.type as ApiErrorType; |
| 53 | if (body.error?.message) message = body.error.message; |
| 54 | } catch { |
| 55 | /* non-JSON error body (e.g. 429 from throttle) — keep defaults */ |
| 56 | } |
| 57 | throw new ApiError(res.status, type, message, retryAfter); |
| 58 | } |
| 59 | return (await res.json()) as T; |
| 60 | } |
no test coverage detected