Files
zipline/src/lib/fetchApi.ts
dicedtomato ef6e0e00a0 feat: response validation (#1012)
* feat: add response schemas (WIP, hella unstable!!)

* refactor: models to zod

* feat: descriptions for api routes

* fix: finish up api refactor

* refactor: generalized error codes

* fix: responses + add descriptions

* fix: more

* fix: lint

* fix: settings errors

* fix: add errors to spec
2026-03-03 16:32:50 -08:00

43 lines
1.0 KiB
TypeScript

import { ApiErrorPayload } from './api/errors';
const bodyMethods = ['POST', 'PUT', 'PATCH', 'DELETE'];
export async function fetchApi<Response = any>(
route: string,
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' = 'GET',
body: any = null,
headers: Record<string, string> = {},
): Promise<{
data: Response | null;
error: ApiErrorPayload | null;
}> {
let data: Response | null = null;
let error: ApiErrorPayload | null = null;
if ((bodyMethods.includes(method) && body !== null) || (body && !Object.keys(body).length)) {
headers['Content-Type'] = 'application/json';
}
const res = await fetch(route, {
method,
headers,
body: body ? JSON.stringify(body) : null,
});
if (res.ok) {
data = await res.json();
} else {
if (res.headers.get('Content-Type')?.startsWith('application/json')) {
error = await res.json();
} else {
error = {
code: 9000,
error: await res.text(),
statusCode: res.status,
} as ApiErrorPayload;
}
}
return { data, error };
}