177 lines
6.6 KiB
TypeScript
177 lines
6.6 KiB
TypeScript
import toast from "react-hot-toast";
|
|
import { API_BASE_URL } from "./runtime-config";
|
|
|
|
export { API_BASE_URL } from "./runtime-config";
|
|
|
|
export interface CurrentUser {
|
|
id: string;
|
|
userName: string;
|
|
displayName: string;
|
|
roles: string[];
|
|
}
|
|
|
|
export interface ApiProblem {
|
|
title?: string;
|
|
detail?: string;
|
|
status?: number;
|
|
errors?: Record<string, string[]>;
|
|
code?: string;
|
|
traceId?: string;
|
|
}
|
|
|
|
export const AUTH_INVALIDATED_EVENT = "inogen:auth-invalidated";
|
|
export const AUTH_CLEARED_EVENT = "inogen:auth-cleared";
|
|
|
|
export function safeApiMessage(status: number, code?: string, traceId?: string): string {
|
|
const known: Record<string, string> = {
|
|
invalid_csrf: "نشست امنیتی معتبر نیست. صفحه را تازهسازی کنید.",
|
|
concurrency_conflict: "داده تغییر کرده است. دوباره تلاش کنید.",
|
|
not_found: "مورد درخواستی پیدا نشد.",
|
|
};
|
|
const message = known[code ?? ""] ?? ({ 400: "درخواست معتبر نیست.", 401: "نشست شما پایان یافته است.",
|
|
403: "دسترسی به این عملیات مجاز نیست.", 409: "داده تغییر کرده است.", 422: "دادههای واردشده معتبر نیست.",
|
|
423: "سامانه در حال حاضر آماده نیست.", 500: "خطای پیشبینینشدهای رخ داد." } as Record<number, string>)[status]
|
|
?? "درخواست انجام نشد.";
|
|
return status >= 500 && traceId && /^[\w.-]{1,120}$/.test(traceId)
|
|
? `${message} کد پیگیری: ${traceId}` : message;
|
|
}
|
|
|
|
type RequestOptions = RequestInit & {
|
|
redirectOnUnauthorized?: boolean;
|
|
skipCsrf?: boolean;
|
|
};
|
|
|
|
export function buildQuery(values: Record<string, unknown>): string {
|
|
const query = new URLSearchParams();
|
|
Object.entries(values).forEach(([key, value]) => {
|
|
if (value == null || value === "") return;
|
|
if (Array.isArray(value)) {
|
|
value.forEach((item) => query.append(key, String(item)));
|
|
return;
|
|
}
|
|
query.set(key, String(value));
|
|
});
|
|
const text = query.toString();
|
|
return text ? `?${text}` : "";
|
|
}
|
|
|
|
class ApiService {
|
|
private csrfToken: string | null = null;
|
|
|
|
private handleSessionExpired(message?: string) {
|
|
this.csrfToken = null;
|
|
window.dispatchEvent(new Event(AUTH_INVALIDATED_EVENT));
|
|
try {
|
|
sessionStorage.setItem("sessionExpired", "1");
|
|
} catch {}
|
|
if (message) toast.error(message);
|
|
if (window.location.pathname !== "/login" && window.location.pathname !== "/admin/login")
|
|
window.location.assign(window.location.pathname.startsWith("/admin") ? "/admin/login" : "/login");
|
|
}
|
|
|
|
private async ensureCsrfToken(): Promise<string> {
|
|
if (this.csrfToken) return this.csrfToken;
|
|
const response = await fetch(`${API_BASE_URL}/auth/csrf`, {
|
|
credentials: "include",
|
|
headers: { Accept: "application/json" },
|
|
});
|
|
if (!response.ok) throw new Error("دریافت توکن امنیتی ناموفق بود.");
|
|
const body = (await response.json()) as { requestToken?: string };
|
|
if (!body.requestToken) throw new Error("توکن امنیتی معتبر دریافت نشد.");
|
|
this.csrfToken = body.requestToken;
|
|
return body.requestToken;
|
|
}
|
|
|
|
private async readError(response: Response): Promise<string> {
|
|
try {
|
|
const problem = (await response.json()) as ApiProblem;
|
|
return safeApiMessage(response.status, problem.code, problem.traceId);
|
|
} catch {
|
|
return safeApiMessage(response.status);
|
|
}
|
|
}
|
|
|
|
private async request<T>(endpoint: string, options: RequestOptions = {}): Promise<T> {
|
|
const method = (options.method || "GET").toUpperCase();
|
|
const unsafe = !["GET", "HEAD", "OPTIONS"].includes(method);
|
|
const headers = new Headers(options.headers);
|
|
if (options.body && !(options.body instanceof FormData) && !headers.has("Content-Type")) {
|
|
headers.set("Content-Type", "application/json");
|
|
}
|
|
headers.set("Accept", "application/json");
|
|
if (unsafe && !options.skipCsrf) headers.set("X-CSRF-TOKEN", await this.ensureCsrfToken());
|
|
|
|
let response: Response;
|
|
try {
|
|
response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
|
...options,
|
|
headers,
|
|
credentials: "include",
|
|
});
|
|
} catch (error) {
|
|
if (error instanceof TypeError) throw new Error("شبکه یا سرویس گزارش در دسترس نیست.");
|
|
throw error;
|
|
}
|
|
|
|
if (response.status === 401 && endpoint !== "/auth/login") {
|
|
if (options.redirectOnUnauthorized !== false)
|
|
this.handleSessionExpired("نشست شما منقضی شده است. لطفاً دوباره وارد شوید.");
|
|
else window.dispatchEvent(new Event(AUTH_INVALIDATED_EVENT));
|
|
}
|
|
if (!response.ok) throw new Error(await this.readError(response));
|
|
if (response.status === 204) return undefined as T;
|
|
return (await response.json()) as T;
|
|
}
|
|
|
|
get<T>(endpoint: string, options: RequestOptions = {}) {
|
|
return this.request<T>(endpoint, { ...options, method: "GET" });
|
|
}
|
|
|
|
post<T>(endpoint: string, data?: unknown, options: RequestOptions = {}) {
|
|
return this.request<T>(endpoint, {
|
|
...options,
|
|
method: "POST",
|
|
body: data === undefined ? undefined : JSON.stringify(data),
|
|
});
|
|
}
|
|
|
|
put<T>(endpoint: string, data?: unknown, options: RequestOptions = {}) {
|
|
return this.request<T>(endpoint, {
|
|
...options,
|
|
method: "PUT",
|
|
body: data === undefined ? undefined : JSON.stringify(data),
|
|
});
|
|
}
|
|
|
|
async login(userName: string, password: string): Promise<CurrentUser> {
|
|
await this.post<void>("/auth/login", { userName, password, rememberMe: true }, {
|
|
redirectOnUnauthorized: false,
|
|
});
|
|
this.csrfToken = null;
|
|
return this.get<CurrentUser>("/auth/me", { redirectOnUnauthorized: false });
|
|
}
|
|
|
|
async logout(): Promise<void> {
|
|
try { await this.post<void>("/auth/logout", undefined, { redirectOnUnauthorized: false }); }
|
|
finally { this.csrfToken = null; window.dispatchEvent(new Event(AUTH_CLEARED_EVENT)); }
|
|
}
|
|
|
|
currentUser(): Promise<CurrentUser> {
|
|
return this.get<CurrentUser>("/auth/me", { redirectOnUnauthorized: false });
|
|
}
|
|
|
|
filePreviewUrl(attachmentId: string): string {
|
|
return `${API_BASE_URL}/files/${encodeURIComponent(attachmentId)}/preview`;
|
|
}
|
|
|
|
async download(endpoint: string): Promise<Blob> {
|
|
const response = await fetch(`${API_BASE_URL}${endpoint}`, { credentials: "include" });
|
|
if (response.status === 401) this.handleSessionExpired();
|
|
if (!response.ok) throw new Error(await this.readError(response));
|
|
return response.blob();
|
|
}
|
|
}
|
|
|
|
const apiService = new ApiService();
|
|
export default apiService;
|