Skip to article
Documentation

src/lib/fetch-json.ts

Linked repository file from this build.

/**
 * Fetch an API route and return its JSON body as `T`.
 * A non-2xx answer throws an Error with the route's `error` message, or `fallback`.
 */
export async function fetchJson<T>(url: string, init: RequestInit & { fallback: string }) {
  const { fallback, ...request } = init;
  const response = await fetch(url, request);
  const body: unknown = await response.json().catch(() => null);
  if (!response.ok) {
    const message =
      body && typeof body === "object" && "error" in body && typeof body.error === "string"
        ? body.error
        : fallback;
    throw new Error(message);
  }
  return body as T;
}