32 lines
863 B
TypeScript
32 lines
863 B
TypeScript
import type { AxiosError } from "axios";
|
|
|
|
import { getAuthLoginRedirectUrl, isAtLoginRedirectUrl } from "./utils";
|
|
|
|
let isRedirectingToLogin = false;
|
|
|
|
function shouldRedirectToLogin(error: unknown): boolean {
|
|
if (!error || typeof error !== "object") return false;
|
|
|
|
const axiosError = error as AxiosError;
|
|
const status = axiosError.response?.status;
|
|
const code = axiosError.code;
|
|
|
|
return status === 401 || code === "UNAUTHORIZED";
|
|
}
|
|
|
|
function redirectToLogin(): void {
|
|
if (typeof window === "undefined") return;
|
|
|
|
const loginUrl = getAuthLoginRedirectUrl();
|
|
if (isAtLoginRedirectUrl(loginUrl)) return;
|
|
if (isRedirectingToLogin) return;
|
|
|
|
isRedirectingToLogin = true;
|
|
window.location.assign(loginUrl);
|
|
}
|
|
|
|
export function errorInterceptor(error: unknown) {
|
|
if (shouldRedirectToLogin(error)) redirectToLogin();
|
|
return Promise.reject(error);
|
|
}
|