Files
tesseract/web/src/api.ts

61 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-11-12 00:31:10 +00:00
import { promiseOrThrow } from "./lib/errors";
2024-12-03 11:32:21 +00:00
interface ApiErrorDetails {
2024-12-02 13:45:49 +00:00
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-12-03 11:32:21 +00:00
type ApiError =
| { type: "NOT_FOUND" }
| { type: "NETWORK" }
| { type: "CONFLICT" }
| { type: "INTERNAL" }
| { type: "BAD_REQUEST"; details: ApiErrorDetails };
2024-11-12 00:31:10 +00:00
async function fetchApi(
url: URL | RequestInfo,
init?: RequestInit,
): Promise<Response> {
const res = await promiseOrThrow(
fetch(`${import.meta.env.VITE_API_URL}/api${url}`, init),
2024-12-03 11:32:21 +00:00
() => ({ type: "NETWORK" }),
2024-11-12 00:31:10 +00:00
);
if (res.status !== 200) {
switch (res.status) {
2024-12-02 13:45:49 +00:00
case 400:
2024-12-03 11:32:21 +00:00
throw {
type: "BAD_REQUEST",
details: await res.json(),
};
2024-11-12 00:31:10 +00:00
case 404:
2024-12-03 11:32:21 +00:00
throw { type: "NOT_FOUND" };
case 409:
throw { type: "CONFLICT" };
2024-11-12 00:31:10 +00:00
default:
2024-12-03 11:32:21 +00:00
throw { type: "INTERNAL" };
2024-11-12 00:31:10 +00:00
}
}
return res;
}
2024-12-03 11:32:21 +00:00
function isApiErrorResponse(error: unknown): error is ApiErrorDetails {
2024-12-02 13:45:49 +00:00
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,
fetchApi,
isApiErrorResponse,
};
2024-12-03 11:32:21 +00:00
export type { ApiError, ApiErrorDetails };