Files
sorsfonalak/services/frontend/src/lib/api.ts
T

46 lines
1.4 KiB
TypeScript
Raw Normal View History

// Backend calls from the browser, through the frontend's /api/v1 proxy.
export class ApiError extends Error {
constructor(
public status: number,
public code: string,
message: string,
public details?: unknown,
) {
super(message);
}
}
export async function api<T = unknown>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> {
const res = await fetch(`/api/v1${path}`, {
method: init.method ?? (init.body === undefined ? "GET" : "POST"),
headers: init.body === undefined ? undefined : { "content-type": "application/json" },
body: init.body === undefined ? undefined : JSON.stringify(init.body),
credentials: "same-origin",
});
const text = await res.text();
const data = text ? JSON.parse(text) : null;
if (!res.ok) {
const err = data?.error ?? {};
throw new ApiError(res.status, err.code ?? "error", err.message ?? `HTTP ${res.status}`, err);
}
return data as T;
}
/** A readable Hungarian message for an API error. */
export function errorText(e: unknown): string {
if (e instanceof ApiError) {
switch (e.code) {
case "unauthorized":
return "Lejárt a munkamenet, lépj be újra.";
case "forbidden":
return "Ehhez nincs jogosultságod.";
case "insufficient_credits":
return "Nincs elég kredited.";
default:
return e.message;
}
}
return "Nem sikerült kapcsolódni a szerverhez. Próbáld újra.";
}