frontPanel/src/api/makeRequest.ts

56 lines
1.7 KiB
TypeScript
Raw Normal View History

import * as KIT from "@frontend/kitui";
import { Method, ResponseType, AxiosError } from "axios";
2024-05-16 13:40:52 +00:00
import { redirect } from "react-router-dom";
import { clearAuthToken } from "@frontend/kitui";
2024-05-16 13:40:52 +00:00
import { cleanAuthTicketData } from "@root/ticket";
import { clearUserData } from "@root/user";
import { clearQuizData } from "@root/quizes/store";
2024-05-13 13:24:41 +00:00
import type { AxiosResponse } from "axios";
import { selectSendingMethod } from "@/ui_kit/FloatingSupportChat/utils";
2024-05-13 13:24:41 +00:00
2024-04-17 14:16:49 +00:00
interface MakeRequest {
method?: Method | undefined;
url: string;
body?: unknown;
useToken?: boolean | undefined;
contentType?: boolean | undefined;
responseType?: ResponseType | undefined;
signal?: AbortSignal | undefined;
withCredentials?: boolean | undefined;
}
2024-05-13 13:24:41 +00:00
type ExtendedAxiosResponse = AxiosResponse & { message: string };
export const makeRequest = async <TRequest = unknown, TResponse = unknown>(
2024-04-17 14:16:49 +00:00
data: MakeRequest,
2024-05-13 13:24:41 +00:00
): Promise<TResponse> => {
2024-04-17 14:16:49 +00:00
try {
2024-05-13 13:24:41 +00:00
const response = await KIT.makeRequest<unknown, TResponse>(data);
return response;
} catch (nativeError) {
const error = nativeError as AxiosError;
2025-04-03 19:22:15 +00:00
// if (window.location.hostname !== 'localhost') selectSendingMethod({
// messageField: `status: ${error.response?.status}. Message ${(error.response?.data as ExtendedAxiosResponse)?.message}`,
// isSnackbar: false,
// systemError: true
// });
2024-04-17 14:16:49 +00:00
if (
error.response?.status === 400 &&
2024-05-13 13:24:41 +00:00
(error.response?.data as ExtendedAxiosResponse)?.message ===
"refreshToken is empty"
2024-04-17 14:16:49 +00:00
) {
cleanAuthTicketData();
clearAuthToken();
clearUserData();
clearQuizData();
redirect("/");
}
2024-05-13 13:24:41 +00:00
throw nativeError;
2024-04-17 14:16:49 +00:00
}
2024-05-13 13:24:41 +00:00
};