Files
tesseract/web/src/api.ts

57 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-11-12 00:31:10 +00:00
import { promiseOrThrow } from "./lib/errors";
2024-12-02 13:45:49 +00:00
interface ApiErrorResponse {
code: string;
error: string;
}
const API_ERROR_BAD_TEMPLATE = "BAD_TEMPLATE";
2024-12-02 19:12:26 +00:00
const API_ERROR_WORKSPACE_EXISTS = "WORKSPACE_EXISTS";
2024-12-02 13:45:49 +00:00
2024-11-12 00:31:10 +00:00
enum ApiError {
NotFound = "NOT_FOUND",
BadRequest = "BAD_REQUEST",
Internal = "INTERNAL",
Network = "NETWORK",
}
async function fetchApi(
url: URL | RequestInfo,
init?: RequestInit,
): Promise<Response> {
const res = await promiseOrThrow(
fetch(`${import.meta.env.VITE_API_URL}/api${url}`, init),
() => ApiError.Network,
);
if (res.status !== 200) {
switch (res.status) {
2024-12-02 13:45:49 +00:00
case 400:
throw await res.json();
2024-11-12 00:31:10 +00:00
case 404:
throw ApiError.NotFound;
default:
throw ApiError.Internal;
}
}
return res;
}
2024-12-02 13:45:49 +00:00
function isApiErrorResponse(error: unknown): error is ApiErrorResponse {
return (
error !== null &&
error !== undefined &&
typeof error === "object" &&
"code" in error &&
"error" in error
);
}
2024-12-02 19:12:26 +00:00
export {
API_ERROR_BAD_TEMPLATE,
API_ERROR_WORKSPACE_EXISTS,
ApiError,
fetchApi,
isApiErrorResponse,
};
2024-12-02 13:45:49 +00:00
export type { ApiErrorResponse };