100 lines
2.5 KiB
TypeScript
100 lines
2.5 KiB
TypeScript
import axios, { AxiosInstance, AxiosResponse, AxiosError } from "axios";
|
|
import toast from "react-hot-toast";
|
|
|
|
class ApiService {
|
|
private api: AxiosInstance;
|
|
|
|
constructor() {
|
|
this.api = axios.create({
|
|
baseURL: import.meta.env.VITE_API_URL || "http://localhost:3001/api",
|
|
timeout: 10000,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
});
|
|
|
|
this.setupInterceptors();
|
|
}
|
|
|
|
private setupInterceptors() {
|
|
this.api.interceptors.request.use(
|
|
(config) => {
|
|
const token = localStorage.getItem("admin_token");
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
},
|
|
(error) => {
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
this.api.interceptors.response.use(
|
|
(response: AxiosResponse) => {
|
|
return response;
|
|
},
|
|
(error: AxiosError) => {
|
|
this.handleError(error);
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
}
|
|
|
|
private handleError(error: AxiosError) {
|
|
if (error.response?.status === 401) {
|
|
localStorage.removeItem("admin_token");
|
|
localStorage.removeItem("admin_user");
|
|
window.location.href = "/login";
|
|
return;
|
|
}
|
|
|
|
const message = this.getErrorMessage(error);
|
|
toast.error(message);
|
|
}
|
|
|
|
private getErrorMessage(error: AxiosError): string {
|
|
if (error.response?.data) {
|
|
const data = error.response.data as any;
|
|
return data.message || data.error || "خطایی رخ داده است";
|
|
}
|
|
|
|
if (error.code === "NETWORK_ERROR") {
|
|
return "خطا در اتصال به سرور";
|
|
}
|
|
|
|
if (error.code === "TIMEOUT") {
|
|
return "درخواست منقضی شد";
|
|
}
|
|
|
|
return "خطای غیرمنتظرهای رخ داده است";
|
|
}
|
|
|
|
async get<T>(url: string, params?: any): Promise<T> {
|
|
const response = await this.api.get(url, { params });
|
|
return response.data;
|
|
}
|
|
|
|
async post<T>(url: string, data?: any): Promise<T> {
|
|
const response = await this.api.post(url, data);
|
|
return response.data;
|
|
}
|
|
|
|
async put<T>(url: string, data?: any): Promise<T> {
|
|
const response = await this.api.put(url, data);
|
|
return response.data;
|
|
}
|
|
|
|
async delete<T>(url: string): Promise<T> {
|
|
const response = await this.api.delete(url);
|
|
return response.data;
|
|
}
|
|
|
|
async patch<T>(url: string, data?: any): Promise<T> {
|
|
const response = await this.api.patch(url, data);
|
|
return response.data;
|
|
}
|
|
}
|
|
|
|
export const apiService = new ApiService();
|