74 lines
2.6 KiB
TypeScript
74 lines
2.6 KiB
TypeScript
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,
|
|
};
|