lms-frontend/src/core/helper/api.ts

31 lines
781 B
TypeScript

import { FetchArgs, fetchBaseQuery } from "@reduxjs/toolkit/query";
import { Constants, handleLogout } from "core/utils/utils";
export function getApiHeader() {
return {
"X-Authorization": localStorage.getItem("session") || "",
};
}
const baseQuery = fetchBaseQuery({
baseUrl: Constants.API_ADDRESS,
prepareHeaders: (headers) => {
headers.set("X-Authorization", localStorage.getItem("session") || "");
return headers;
},
});
export const baseQueryWithErrorHandling = async (
args: string | FetchArgs,
api: any,
extraOptions: any
) => {
const result = await baseQuery(args, api, extraOptions);
if (result.error && result.error.status === 401) {
console.error("Unauthorized. Please log in again.");
handleLogout();
}
return result;
};