initial commit

This commit is contained in:
Antigravity
2026-11-18 18:06:22 +05:30
commit 13556aa423
229 changed files with 58732 additions and 0 deletions
+73
View File
@@ -0,0 +1,73 @@
const BASE_URL = "/api";
export class ApiError extends Error {
constructor(
public status: number,
public detail: string,
public code?: string
) {
super(detail);
}
}
let onUnauthorizedCallback: (() => void) | null = null;
export function setUnauthorizedHandler(cb: () => void) {
onUnauthorizedCallback = cb;
}
function handleUnauthorized(path: string) {
sessionStorage.removeItem("access_token");
if (!path.startsWith("/auth/login")) {
onUnauthorizedCallback?.();
}
}
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const token = sessionStorage.getItem("access_token");
const isFormData = typeof FormData !== "undefined" && options.body instanceof FormData;
const headers: Record<string, string> = {
...(isFormData ? {} : { "Content-Type": "application/json" }),
...(options.headers as Record<string, string>),
};
if (token) headers["Authorization"] = `Bearer ${token}`;
const res = await fetch(`${BASE_URL}${path}`, { ...options, headers });
if (!res.ok) {
const body = await res.json().catch(() => ({ detail: res.statusText }));
if (res.status === 401) handleUnauthorized(path);
throw new ApiError(res.status, body.detail ?? res.statusText, body.code);
}
if (res.status === 204) return undefined as T;
return res.json();
}
async function downloadBlob(path: string): Promise<{ blob: Blob; contentType: string }> {
const token = sessionStorage.getItem("access_token");
const headers: Record<string, string> = {};
if (token) headers["Authorization"] = `Bearer ${token}`;
const res = await fetch(`${BASE_URL}${path}`, { headers });
if (!res.ok) {
const body = await res.json().catch(() => ({ detail: res.statusText }));
if (res.status === 401) handleUnauthorized(path);
throw new ApiError(res.status, body.detail ?? res.statusText, body.code);
}
const blob = await res.blob();
const contentType = res.headers.get("Content-Type") || blob.type || "application/octet-stream";
return { blob, contentType };
}
export const api = {
get: <T>(path: string) => request<T>(path),
post: <T>(path: string, data?: unknown) =>
request<T>(path, { method: "POST", body: data !== undefined ? JSON.stringify(data) : undefined }),
patch: <T>(path: string, data: unknown) =>
request<T>(path, { method: "PATCH", body: JSON.stringify(data) }),
put: <T>(path: string, data: unknown) =>
request<T>(path, { method: "PUT", body: JSON.stringify(data) }),
delete: <T>(path: string) => request<T>(path, { method: "DELETE" }),
upload: <T>(path: string, formData: FormData) =>
request<T>(path, { method: "POST", body: formData }),
downloadBlob,
};