65 lines
2.8 KiB
TypeScript
65 lines
2.8 KiB
TypeScript
import type { ApiProblem } from "../types";
|
|
import { API_ORIGIN } from "../../lib/runtime-config";
|
|
import { AUTH_CLEARED_EVENT, AUTH_INVALIDATED_EVENT, safeApiMessage } from "../../lib/api";
|
|
|
|
export const apiOrigin = API_ORIGIN;
|
|
let csrfToken: string | null = null;
|
|
const getCache = new Map<string, { expires: number; value: Promise<unknown> }>();
|
|
const getCacheTtlMs = 30_000;
|
|
if (typeof window !== "undefined") {
|
|
for (const event of [AUTH_CLEARED_EVENT, AUTH_INVALIDATED_EVENT])
|
|
window.addEventListener(event, () => { csrfToken = null; getCache.clear(); });
|
|
}
|
|
|
|
export class ApiError extends Error {
|
|
constructor(public status: number, public problem: ApiProblem) {
|
|
super(safeApiMessage(status, problem.code, problem.traceId));
|
|
}
|
|
}
|
|
|
|
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.dispatchEvent(new Event(AUTH_INVALIDATED_EVENT));
|
|
if (window.location.pathname !== "/admin/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>;
|
|
}
|