42 lines
1.1 KiB
TypeScript
42 lines
1.1 KiB
TypeScript
export async function api<T = Record<string, unknown>>(
|
|
path: string,
|
|
body?: unknown,
|
|
method = body === undefined ? "GET" : "POST",
|
|
): Promise<T> {
|
|
let response: Response;
|
|
try {
|
|
response = await fetch("/api/v1/" + path, {
|
|
signal: AbortSignal.timeout(30000),
|
|
cache: "no-store",
|
|
method,
|
|
headers:
|
|
body === undefined ? undefined : { "Content-Type": "application/json" },
|
|
body: body === undefined ? undefined : 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;
|
|
}
|