import axios, { AxiosResponse, Method } from "axios"; import { getAuthToken, setAuthToken } from "../stores/auth"; export async function makeRequest({ method = "post", url, body, useToken = true, contentType = false, signal, withCredentials, }: { method?: Method; url: string; body?: TRequest; /** Send access token */ useToken?: boolean; contentType?: boolean; signal?: AbortSignal; /** Send refresh token */ withCredentials?: boolean; }): Promise { const headers: Record = {}; if (useToken) headers["Authorization"] = `Bearer ${getAuthToken()}`; if (contentType) headers["Content-Type"] = "application/json"; try { const response = await axios>({ url, method, headers, data: body, signal, withCredentials, }); if (response.data?.accessToken) { setAuthToken(response.data.accessToken); } return response.data; } catch (error) { if (axios.isAxiosError(error) && error.response?.status === 401 && !withCredentials) { const refreshResponse = await refresh(getAuthToken()); if (refreshResponse.data?.accessToken) setAuthToken(refreshResponse.data.accessToken); headers["Authorization"] = refreshResponse.data.accessToken; const response = await axios.request>({ url, method, headers, data: body, signal, }); return response.data; } throw error; } } function refresh(token: string) { return axios>("https://admin.pena.digital/auth/refresh", { headers: { "Authorization": token, "Content-Type": "application/json", }, }); }