157 lines
5.1 KiB
TypeScript
157 lines
5.1 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;
|
|
}
|
|
|
|
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) {
|
|
try {
|
|
sessionStorage.setItem("sessionExpired", "1");
|
|
} catch {}
|
|
if (message) toast.error(message);
|
|
if (window.location.pathname !== "/login") window.location.assign("/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;
|
|
const validation = problem.errors
|
|
? Object.values(problem.errors).flat().filter(Boolean).join(" ")
|
|
: "";
|
|
return validation || problem.detail || problem.title || `خطای HTTP ${response.status}`;
|
|
} catch {
|
|
return `خطای HTTP ${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 && options.redirectOnUnauthorized !== false) {
|
|
this.handleSessionExpired("نشست شما منقضی شده است. لطفاً دوباره وارد شوید.");
|
|
}
|
|
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> {
|
|
await this.post<void>("/auth/logout");
|
|
this.csrfToken = null;
|
|
}
|
|
|
|
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;
|