Show the backend's Persian error (errors[0].message, e.g. rate-limit 'درخواستهای زیاد') as a toast for any failed request.* call, from the axios response interceptor — so failures are no longer silent. 401 still logs out/redirects without a toast; callers can opt out with config.skipErrorToast. Drop now-redundant per-caller alerts/toasts in the booking submit, payment, and OTP userinfo paths. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
68 lines
1.9 KiB
JavaScript
68 lines
1.9 KiB
JavaScript
import axios from "axios";
|
|
import Cookies from "js-cookie";
|
|
import { toast } from "react-toastify";
|
|
|
|
function extractErrorMessage(error) {
|
|
const errors = error?.response?.data?.errors;
|
|
if (Array.isArray(errors) && errors.length > 0 && errors[0]?.message) {
|
|
return errors[0].message;
|
|
}
|
|
if (error?.response?.data?.message) {
|
|
return error.response.data.message;
|
|
}
|
|
return "خطایی رخ داد. لطفاً دوباره تلاش کنید.";
|
|
}
|
|
|
|
const BASE_URL = process.env.NEXT_PUBLIC_API_URL;
|
|
|
|
const api = axios.create({
|
|
baseURL: BASE_URL,
|
|
"X-CSRF-Token": "",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
});
|
|
|
|
// اضافه کردن interceptor برای افزودن token به ریکوستهایی که نیاز به احراز هویت دارند
|
|
api.interceptors.request.use(
|
|
(config) => {
|
|
// فقط اگر requireAuth در config تنظیم شده باشد، token اضافه میشود
|
|
if (config.requireAuth) {
|
|
const token = Cookies.get("access_token");
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
}
|
|
return config;
|
|
},
|
|
(error) => {
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
api.interceptors.response.use(
|
|
(response) => {
|
|
return response.data;
|
|
},
|
|
(error) => {
|
|
if (typeof window !== "undefined") {
|
|
if (error?.response?.status === 401) {
|
|
const hostname = window.location.hostname;
|
|
const domain = hostname.includes("localhost")
|
|
? undefined
|
|
: `.${hostname.split(".").slice(-2).join(".")}`;
|
|
const opts = { path: "/", ...(domain && { domain }) };
|
|
["access_token", "refresh_token", "uuid", "userInfo"].forEach((key) => {
|
|
Cookies.remove(key, opts);
|
|
});
|
|
window.location.href = "/login";
|
|
} else if (!error?.config?.skipErrorToast) {
|
|
toast.error(extractErrorMessage(error));
|
|
}
|
|
}
|
|
return Promise.reject(error);
|
|
}
|
|
);
|
|
|
|
export default api;
|