9ff4c0dbd5
* Setup project-wide prettier * Remove old workspace file * Remove old debugging directives * New top-level .prettierignore * Updated Prettier config settings * Contrubuting guide: Fix for some bad code blocks * Added more ignores * Improved the format script command * printWidth set to 100 * Formatted entire repo (pnpm run format)
31 lines
728 B
TypeScript
31 lines
728 B
TypeScript
import { z } from "zod";
|
|
|
|
export async function zodfetch<TResponseBody extends any>(
|
|
schema: z.Schema<TResponseBody>,
|
|
url: string,
|
|
requestInit?: RequestInit
|
|
): Promise<TResponseBody> {
|
|
const response = await fetch(url, requestInit);
|
|
|
|
if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
|
|
// @ts-ignore
|
|
return;
|
|
}
|
|
|
|
//todo improve error handling
|
|
|
|
if (response.status >= 400 && response.status < 500) {
|
|
const body = await response.json();
|
|
|
|
throw new Error(body.error);
|
|
}
|
|
|
|
if (response.status !== 200) {
|
|
throw new Error(`Failed to fetch ${url}, got status code ${response.status}`);
|
|
}
|
|
|
|
const jsonBody = await response.json();
|
|
|
|
return schema.parse(jsonBody);
|
|
}
|