68 lines
2.3 KiB
TypeScript
68 lines
2.3 KiB
TypeScript
import axios, { type AxiosError, type AxiosResponse } from "axios";
|
|
import { store } from "@/main.ts";
|
|
import { addNewMessage, color } from "@/services/popupDisplayer.ts";
|
|
|
|
const axiosInstance = axios.create({
|
|
baseURL: import.meta.env.VITE_BACKEND_URL,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
});
|
|
|
|
axiosInstance.interceptors.response.use(
|
|
(response) => response, // Directly return successful responses.
|
|
async (error) => {
|
|
const originalRequest = error.config;
|
|
if (
|
|
error.response.status === 401 &&
|
|
!originalRequest._retry &&
|
|
store.authenticated
|
|
) {
|
|
originalRequest._retry = true; // Mark the request as retried to avoid infinite loops.
|
|
try {
|
|
await store.refreshUserToken();
|
|
// Update the authorization header with the new access token.
|
|
axiosInstance.defaults.headers.common["Authorization"] =
|
|
`Bearer ${store.user.token}`;
|
|
return axiosInstance(originalRequest); // Retry the original request with the new access token.
|
|
} catch (refreshError) {
|
|
// Handle refresh token errors by clearing stored tokens and redirecting to the login page.
|
|
console.error("Token refresh failed:", refreshError);
|
|
localStorage.removeItem("accessToken");
|
|
localStorage.removeItem("refreshToken");
|
|
window.location.href = "/login";
|
|
return Promise.reject(refreshError);
|
|
}
|
|
}
|
|
return Promise.reject(error); // For all other errors, return the error as is.
|
|
}
|
|
);
|
|
|
|
// TODO: spawn a error modal
|
|
function defaultApiErrorHandler(err: AxiosError) {
|
|
addNewMessage(err.message, color.Red);
|
|
}
|
|
|
|
function defaultApiSuccessHandler(response: AxiosResponse) {
|
|
addNewMessage(response.data, color.Green);
|
|
}
|
|
|
|
function callApi(
|
|
endpoint: string,
|
|
onSuccessHandler?: (response: AxiosResponse) => void,
|
|
onErrorHandler?: (error: AxiosError) => void
|
|
): void {
|
|
axiosInstance
|
|
.get(endpoint)
|
|
.then(
|
|
onSuccessHandler == null
|
|
? defaultApiSuccessHandler
|
|
: onSuccessHandler
|
|
)
|
|
.catch(
|
|
onErrorHandler == null ? defaultApiErrorHandler : onErrorHandler
|
|
);
|
|
}
|
|
|
|
export { callApi };
|