File size: 672 Bytes
7d7a53f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import type { Serialize } from "./serialize";
export async function fetchJSON<T>(
url: string,
options?: {
fetch?: typeof window.fetch;
allowNull?: boolean;
}
): Promise<Serialize<T>> {
const response = await (options?.fetch ?? fetch)(url);
if (!response.ok) {
throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
}
// Handle empty responses (which parse to null)
const text = await response.text();
if (!text || text.trim() === "") {
if (options?.allowNull) {
return null as Serialize<T>;
}
throw new Error(`Received empty response from ${url} but allowNull is not set to true`);
}
return JSON.parse(text);
}
|