(
path: string,
options: RequestInit = {},
)
| 28 | } |
| 29 | |
| 30 | export async function apiRequest<T>( |
| 31 | path: string, |
| 32 | options: RequestInit = {}, |
| 33 | ): Promise<T> { |
| 34 | const { headers, ...rest } = options; |
| 35 | const response = await fetch(apiUrl(path), { |
| 36 | ...rest, |
| 37 | headers: apiHeaders(headers), |
| 38 | }); |
| 39 | |
| 40 | const contentType = response.headers.get("content-type") ?? ""; |
| 41 | if (!response.ok) { |
| 42 | let message = `Request failed with status ${response.status}`; |
| 43 | if (contentType.includes("application/json")) { |
| 44 | const body = (await response.json()) as { error?: string }; |
| 45 | message = body.error ?? message; |
| 46 | } else { |
| 47 | message = await response.text(); |
| 48 | } |
| 49 | throw new ApiError(message, response.status); |
| 50 | } |
| 51 | |
| 52 | if (response.status === 204) { |
| 53 | return null as T; |
| 54 | } |
| 55 | |
| 56 | if (contentType.includes("application/json")) { |
| 57 | return (await response.json()) as T; |
| 58 | } |
| 59 | |
| 60 | return (await response.text()) as T; |
| 61 | } |
| 62 | |
| 63 | export async function pairBrowser(code: string): Promise<void> { |
| 64 | await apiRequest<{ ok: boolean }>("/api/pair", { |
no test coverage detected