145 lines
5.1 KiB
TypeScript
145 lines
5.1 KiB
TypeScript
import axios from 'axios';
|
|
import type { AxiosError, InternalAxiosRequestConfig } from 'axios';
|
|
import toast from 'react-hot-toast';
|
|
import { useAdminAuthStore } from '../store/adminAuthStore';
|
|
import type { ApiResponse, AuthResponseData } from '../types/admin';
|
|
|
|
export const BASE_DOMAIN = import.meta.env.VITE_API_URL
|
|
? import.meta.env.VITE_API_URL.replace(/\/api$/, '')
|
|
: (import.meta.env.DEV ? 'http://127.0.0.1:4001' : '');
|
|
|
|
const baseURL = `${BASE_DOMAIN}/api`;
|
|
|
|
export interface ApiErrorPayload {
|
|
success: boolean;
|
|
statusCode: number;
|
|
message: string;
|
|
code: string;
|
|
details?: Array<{ field: string; message: string }> | Record<string, unknown>;
|
|
timestamp?: string;
|
|
path?: string;
|
|
}
|
|
|
|
const api = axios.create({
|
|
baseURL,
|
|
withCredentials: true,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
let isRefreshing = false;
|
|
let failedQueue: Array<{
|
|
resolve: (token: string) => void;
|
|
reject: (reason?: unknown) => void;
|
|
}> = [];
|
|
|
|
const processQueue = (error: unknown, token: string | null = null) => {
|
|
failedQueue.forEach((prom) => {
|
|
if (error) {
|
|
prom.reject(error);
|
|
} else if (token) {
|
|
prom.resolve(token);
|
|
}
|
|
});
|
|
failedQueue = [];
|
|
};
|
|
|
|
api.interceptors.request.use((config: InternalAxiosRequestConfig) => {
|
|
const token = useAdminAuthStore.getState().accessToken;
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
});
|
|
|
|
api.interceptors.response.use(
|
|
(response) => response,
|
|
async (error: AxiosError<ApiErrorPayload>) => {
|
|
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
|
|
const responseData = error.response?.data;
|
|
const status = error.response?.status;
|
|
const farsiMessage = responseData?.message || 'خطایی در ارتباط با سرور رخ داده است.';
|
|
|
|
if (status === 401 && originalRequest && !originalRequest._retry) {
|
|
const currentToken = useAdminAuthStore.getState().accessToken;
|
|
if (!currentToken || originalRequest.url?.includes('/auth/refresh') || originalRequest.url?.includes('/auth/admin-login') || originalRequest.url?.includes('/auth/verify-otp')) {
|
|
useAdminAuthStore.getState().clearAuth();
|
|
if (window.location.pathname !== '/login') {
|
|
toast.error('نشست کاری شما منقضی شده است. لطفاً مجدداً وارد شوید.');
|
|
window.location.href = '/login';
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
|
|
if (isRefreshing) {
|
|
return new Promise((resolve, reject) => {
|
|
failedQueue.push({ resolve, reject });
|
|
})
|
|
.then((token) => {
|
|
originalRequest.headers.Authorization = `Bearer ${token}`;
|
|
return api(originalRequest);
|
|
})
|
|
.catch((err) => Promise.reject(err));
|
|
}
|
|
|
|
originalRequest._retry = true;
|
|
isRefreshing = true;
|
|
|
|
try {
|
|
const refreshResponse = await axios.post<ApiResponse<AuthResponseData>>(
|
|
`${baseURL}/auth/refresh`,
|
|
{},
|
|
{ withCredentials: true }
|
|
);
|
|
|
|
if (refreshResponse.data?.success && refreshResponse.data.data?.accessToken) {
|
|
const newToken = refreshResponse.data.data.accessToken;
|
|
const user = refreshResponse.data.data.user;
|
|
useAdminAuthStore.getState().setAuth(newToken, user);
|
|
processQueue(null, newToken);
|
|
|
|
originalRequest.headers.Authorization = `Bearer ${newToken}`;
|
|
return api(originalRequest);
|
|
} else {
|
|
throw new Error('Refresh failed');
|
|
}
|
|
} catch (refreshErr) {
|
|
processQueue(refreshErr, null);
|
|
useAdminAuthStore.getState().clearAuth();
|
|
if (window.location.pathname !== '/login') {
|
|
toast.error('نشست کاری شما منقضی شده است. لطفاً مجدداً وارد شوید.');
|
|
window.location.href = '/login';
|
|
}
|
|
return Promise.reject(refreshErr);
|
|
} finally {
|
|
isRefreshing = false;
|
|
}
|
|
}
|
|
|
|
if (status === 403) {
|
|
toast.error('دسترسی شما به این بخش از پنل ادمین مجاز نمیباشد.', { id: 'admin-403' });
|
|
(error as unknown as Record<string, boolean>)._toastShown = true;
|
|
} else if (status !== 401 && !(originalRequest as unknown as Record<string, boolean>)?.hideErrorToast) {
|
|
let fullMessage = farsiMessage;
|
|
if (responseData?.details && Array.isArray(responseData.details) && responseData.details.length > 0) {
|
|
const detailStrings = responseData.details
|
|
.map((d: unknown) => typeof d === 'string' ? d : ((d as Record<string, string>)?.message || (d as Record<string, string>)?.field))
|
|
.filter(Boolean);
|
|
if (detailStrings.length > 0) {
|
|
const joinedDetails = detailStrings.join('، ');
|
|
if (!farsiMessage.includes(joinedDetails)) {
|
|
fullMessage = `${farsiMessage} (${joinedDetails})`;
|
|
}
|
|
}
|
|
}
|
|
toast.error(fullMessage, { id: fullMessage });
|
|
(error as unknown as Record<string, boolean>)._toastShown = true;
|
|
}
|
|
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default api;
|