Files
History-client/api/http.ts
2026-04-19 00:13:22 +07:00

31 lines
806 B
TypeScript

export class ApiError extends Error {
status: number;
body: string;
constructor(message: string, status: number, body: string) {
super(message);
this.name = "ApiError";
this.status = status;
this.body = body;
}
}
export async function requestJson<T>(input: RequestInfo | URL, init?: RequestInit): Promise<T> {
const res = await fetch(input, init);
if (!res.ok) {
const text = await res.text();
throw new ApiError(`Request failed with status ${res.status}`, res.status, text);
}
return (await res.json()) as T;
}
export function jsonRequestInit(method: string, body: unknown): RequestInit {
return {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
};
}