/
authApi.ts
35 lines (30 loc) · 973 Bytes
/
authApi.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import axios from "axios";
import { ILoginResponse } from "./types";
const BASE_URL = "http://localhost:8000/api/";
export const authApi = axios.create({
baseURL: BASE_URL,
withCredentials: true,
});
authApi.defaults.headers.common["Content-Type"] = "application/json";
export const refreshAccessTokenFn = async () => {
const response = await authApi.get<ILoginResponse>('auth/refresh');
return response.data;
};
authApi.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
const originalRequest = error.config;
const errMessage = error.response.data.message as string;
if (errMessage.includes('not logged in') && !originalRequest._retry) {
originalRequest._retry = true;
await refreshAccessTokenFn();
return authApi(originalRequest);
}
if (error.response.data.message.includes('not refresh')) {
document.location.href = '/login';
}
return Promise.reject(error);
}
);