import axios, { AxiosInstance, AxiosResponse } from 'axios'; import { logout, setToken } from '../redux/slice/auth'; import { store } from '../redux/store'; import { refresh } from './authApi'; import i18next from 'i18next'; import { REACT_APP_BASE_URL_API } from '../constant/env'; // Create an Axios instance with a base URL const api: AxiosInstance = axios.create({ baseURL: REACT_APP_BASE_URL_API, timeout: 15000, withCredentials: false, }); api.interceptors.request.use( (config) => { let accessToken = store.getState().auth.accessToken; config.headers['Authorization'] = `Bearer ${accessToken || ''}`; if (!(config.data instanceof FormData)) { config.headers['Content-Type'] = 'application/json'; } else { config.headers['Content-Type'] = 'multipart/form-data'; } // datnd 05/11/2024 const currentLanguage = i18next.language || 'en'; // Default to 'en' if language is not set config.headers['Accept-Language'] = currentLanguage; // config.headers['Access-Control-Allow-Origin'] = '*/*'; return config; }, (error) => { return Promise.reject(error); }, ); api.interceptors.response.use( (response: AxiosResponse) => response, async (error) => { const originalRequest = error.config; if (error.message === 'Network Error') { error.message = 'Mất kết nối internet. Vui lòng kiểm tra lại đường truyền của bạn.'; return Promise.reject(error); } const auth = store.getState().auth; if ( error.response?.status === 401 && !originalRequest._retry && auth.refreshToken && (!error.config?.url?.includes('/customer-auth') || !error.config?.url?.includes('/auth')) ) { try { originalRequest._retry = true; const response = await refresh(auth.refreshToken); store.dispatch(setToken({ accessToken: response!.data.access_token, refreshToken: response!.data.refresh_token })); originalRequest.headers['Authorization'] = `Bearer ${response!.data.access_token}`; return api(originalRequest); } catch (err) { store.dispatch(logout()); return Promise.reject(err); } } else if (error.response?.status === 403) { error.message = 'Bạn không có quyền thực hiện chức năng này! (ERROR_CODE: 403) URL: ' + error.request.responseURL.replace(REACT_APP_BASE_URL_API, ''); // navigate('/login'); } else if (error.response?.status === 422) { error.message = 'Tham số sai Content-Type! (ERROR_CODE: 422)'; } return Promise.reject(error); }, ); export const fileConfig = { headers: { Accept: '*/*', 'Content-Type': 'application/json', }, responseType: 'arraybuffer', }; export const formDataConfig = { headers: { Accept: '*/*', 'Content-Type': 'multipart/form-data', }, }; export default api;