2023-04-17 12:24:09 +00:00
|
|
|
|
import axios from "axios";
|
2023-03-12 02:32:56 +00:00
|
|
|
|
interface MakeRequest {
|
2023-04-17 12:24:09 +00:00
|
|
|
|
method?: string;
|
|
|
|
|
url: string;
|
|
|
|
|
body?: unknown;
|
|
|
|
|
useToken?: boolean;
|
|
|
|
|
contentType?: boolean;
|
|
|
|
|
signal?: AbortSignal;
|
2023-03-12 02:32:56 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default (props: MakeRequest) => {
|
2023-04-17 12:24:09 +00:00
|
|
|
|
return new Promise(async (resolve, reject) => {
|
|
|
|
|
await makeRequest(props)
|
|
|
|
|
.then((r) => resolve(r))
|
|
|
|
|
.catch((r) => reject(r));
|
|
|
|
|
});
|
|
|
|
|
};
|
2023-03-12 02:32:56 +00:00
|
|
|
|
|
2023-04-17 12:24:09 +00:00
|
|
|
|
function makeRequest({ method = "post", url, body, useToken = true, signal, contentType = false }: MakeRequest) {
|
|
|
|
|
//В случае 401 рефреш должен попробовать вызваться 1 раз
|
|
|
|
|
let counterRefresh = true;
|
|
|
|
|
let headers: any = {};
|
|
|
|
|
if (useToken) headers["Authorization"] = localStorage.getItem("AT");
|
|
|
|
|
if (contentType) headers["Content-Type"] = "application/json";
|
|
|
|
|
return axios({
|
|
|
|
|
url: url,
|
|
|
|
|
method: method,
|
|
|
|
|
headers: headers,
|
|
|
|
|
data: body,
|
|
|
|
|
signal,
|
|
|
|
|
})
|
|
|
|
|
.then((response) => {
|
|
|
|
|
if (response.data && response.data.accessToken) {
|
|
|
|
|
localStorage.setItem("AT", response.data.accessToken);
|
|
|
|
|
}
|
|
|
|
|
return response;
|
2023-03-12 02:32:56 +00:00
|
|
|
|
})
|
2023-04-17 12:24:09 +00:00
|
|
|
|
.catch((error) => {
|
|
|
|
|
if (error.response.status == 401 && counterRefresh) {
|
|
|
|
|
refresh().then((response) => {
|
|
|
|
|
if (response.data && response.data.accessToken) localStorage.setItem("AT", response.data.accessToken);
|
|
|
|
|
counterRefresh = false;
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
throw error;
|
|
|
|
|
});
|
2023-03-12 02:32:56 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function refresh() {
|
2023-04-17 12:24:09 +00:00
|
|
|
|
return axios("https://admin.pena.digital/auth/refresh", {
|
|
|
|
|
headers: {
|
|
|
|
|
Authorization: localStorage.getItem("AT"),
|
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|