40 lines
988 B
TypeScript
40 lines
988 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,
|
|
options: { redirectOnUnauthorized?: boolean } = {},
|
|
) {
|
|
if (
|
|
options.redirectOnUnauthorized !== false &&
|
|
shouldRedirectToLogin(error)
|
|
) {
|
|
redirectToLogin();
|
|
}
|
|
return Promise.reject(error);
|
|
}
|