Files
MineGeo/lib/client-api.ts
pavel444-byte 930e00a736
All checks were successful
Deploy MineGeo to Dokploy / deploy (push) Successful in 8m53s
Secure profile photo uploads and trust configured production origin
2026-10-15 14:00:46 +05:00

51 lines
1.4 KiB
TypeScript

export async function api<T = Record<string, unknown>>(
path: string,
body?: unknown,
method = body === undefined ? "GET" : "POST",
): Promise<T> {
let response: Response;
const formData =
typeof FormData !== "undefined" && body instanceof FormData;
try {
response = await fetch("/api/v1/" + path, {
signal: AbortSignal.timeout(30000),
cache: "no-store",
method,
headers:
body === undefined || formData
? undefined
: { "Content-Type": "application/json" },
body:
body === undefined
? undefined
: typeof FormData !== "undefined" && body instanceof FormData
? body
: JSON.stringify(body),
});
} catch (error) {
if (
error instanceof Error &&
["TimeoutError", "AbortError"].includes(error.name)
)
throw new Error("The request timed out. Reconnect and try again.");
throw new Error(
"Could not reach MineGeo. Check your connection and try again.",
);
}
let data: T & { error?: string };
try {
data = await response.json();
} catch {
throw new Error(
"MineGeo returned an unreadable response. Please try again.",
);
}
if (!response.ok)
throw new Error(
typeof data?.error === "string"
? data.error
: "Request failed. Please try again.",
);
return data;
}