import axios from "axios"; const http = axios.create({ baseURL: "http://localhost:5000", headers: { "Cache-Control": "no-cache", Pragma: "no-cache", Expires: "0", }, }); http.interceptors.request.use( (config) => { const token = localStorage.getItem("accessToken"); if (token) { if (config.headers) { config.headers.Authorization = `Bearer ${token}`; } } return config; }, (error) => { return Promise.reject(error); } ); http.interceptors.response.use( (response) => { return response; }, async (error) => { if (error.config.url.includes("/auth")) { return Promise.reject(error); } const originalRequest = error.config; // Handle token expiration and retry the request with a refreshed token if (error.response && error.response.status === 401 && !originalRequest._retry) { originalRequest._retry = true; return await refreshToken() .then(() => { return http(originalRequest); }) .catch(); } return Promise.reject(error); } ); async function refreshToken(): Promise { return new Promise(async (resolve, reject) => { await http .post(`/auth/refresh`, { access: localStorage.getItem("accessToken"), refreshToken: localStorage.getItem("refreshToken"), }) .then((response) => { const { access, refreshToken } = response.data; localStorage.setItem("accessToken", access); localStorage.setItem("refreshToken", refreshToken); resolve(); }) .catch((error) => { console.error("Error refreshing token:", error); reject(); }); }); } export { http };