inogen/app/admin/lib/api.ts
2026-10-18 18:12:59 +03:30

58 lines
2.4 KiB
TypeScript

import type { ApiProblem } from "../types";
import { API_ORIGIN } from "../../lib/runtime-config";
export const apiOrigin = API_ORIGIN;
let csrfToken: string | null = null;
const getCache = new Map<string, { expires: number; value: Promise<unknown> }>();
const getCacheTtlMs = 30_000;
export class ApiError extends Error {
constructor(public status: number, public problem: ApiProblem) {
super(problem.title ?? "خطا در ارتباط با سرور");
}
}
async function getCsrfToken() {
if (csrfToken) return csrfToken;
const response = await fetch(`${apiOrigin}/api/v1/auth/csrf`, { credentials: "include" });
if (!response.ok) throw new Error("دریافت توکن امنیتی ناموفق بود.");
csrfToken = (await response.json() as { requestToken: string }).requestToken;
return csrfToken;
}
export async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
const method = (init.method ?? "GET").toUpperCase();
if (method === "GET") {
const cached = getCache.get(path);
if (cached && cached.expires > Date.now()) return cached.value as Promise<T>;
if (cached) getCache.delete(path);
const value = request<T>(path, init, method).catch(reason => { getCache.delete(path); throw reason; });
getCache.set(path, { expires: Date.now() + getCacheTtlMs, value });
return value;
}
getCache.clear();
return request<T>(path, init, method);
}
async function request<T>(path: string, init: RequestInit, method: string): Promise<T> {
const headers = new Headers(init.headers);
headers.set("Accept", "application/json");
if (init.body && !(init.body instanceof FormData)) headers.set("Content-Type", "application/json");
if (!["GET", "HEAD", "OPTIONS"].includes(method)) headers.set("X-CSRF-TOKEN", await getCsrfToken());
const response = await fetch(`${apiOrigin}${path}`, { ...init, headers, credentials: "include" });
if (response.status === 401) {
csrfToken = null; getCache.clear();
if (!path.endsWith("/login")) window.location.assign("/admin/login");
}
if (!response.ok) {
let problem: ApiProblem = { title: `خطای ${response.status}` };
try { problem = await response.json() as ApiProblem; } catch { /* non-json response */ }
throw new ApiError(response.status, problem);
}
if (path.endsWith("/auth/login")) { csrfToken = null; getCache.clear(); }
if (response.status === 204) return undefined as T;
return response.json() as Promise<T>;
}