Open History to see the last commit
1import { fakeFetch } from "./fake-fetch";
2import type { ApiErrorBody } from "./fake-server";
3
4/** A non-2xx response. Mutation handlers let it throw, which rolls the optimistic change back. */
5export class ApiError extends Error {
6 constructor(
7 readonly status: number,
8 readonly code: string,
9 message: string,
10 ) {
11 super(message);
12 this.name = "ApiError";
13 }
14}
15
16async function request<T>(
17 method: string,
18 url: string,
19 { body, signal }: { body?: unknown; signal?: AbortSignal } = {},
20): Promise<T> {
21 const response = await fakeFetch(url, {
22 method,
23 signal,
24 headers: body === undefined ? undefined : { "Content-Type": "application/json" },
25 body: body === undefined ? undefined : JSON.stringify(body),
26 });
27 if (!response.ok) {
28 const { error } = (await response.json()) as ApiErrorBody;
29 throw new ApiError(response.status, error.code, error.message);
30 }
31 return response.status === 204 ? (undefined as T) : ((await response.json()) as T);
32}
33
34/** JSON over `fakeFetch`. Throws an `ApiError` for any non-2xx response. */
35export const api = {
36 get: <T>(url: string, options?: { signal?: AbortSignal }) => request<T>("GET", url, options),
37 post: <T>(url: string, body: unknown) => request<T>("POST", url, { body }),
38 patch: <T>(url: string, body: unknown) => request<T>("PATCH", url, { body }),
39 delete: (url: string) => request<void>("DELETE", url),
40};