-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient.ts
More file actions
94 lines (80 loc) · 2.5 KB
/
client.ts
File metadata and controls
94 lines (80 loc) · 2.5 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import axios, { type AxiosInstance } from "axios";
import { reissueAccessTokenApi } from "@/lib/api/auth";
import { isTokenExpired } from "@/lib/utils/jwtUtils";
import {
loadAccessToken,
loadRefreshToken,
removeAccessToken,
removeRefreshToken,
saveAccessToken,
} from "@/lib/utils/localStorage";
const convertToBearer = (token: string) => `Bearer ${token}`;
const API_SERVER_URL = import.meta.env.VITE_API_SERVER_URL?.trim();
if (!API_SERVER_URL) {
throw new Error("[admin] VITE_API_SERVER_URL is required. Configure it in your environment.");
}
export const axiosInstance: AxiosInstance = axios.create({
baseURL: API_SERVER_URL,
withCredentials: true,
});
axiosInstance.interceptors.request.use(
async (config) => {
const newConfig = { ...config };
let accessToken: string | null = loadAccessToken();
if (accessToken === null || isTokenExpired(accessToken)) {
const refreshToken = loadRefreshToken();
if (refreshToken === null || isTokenExpired(refreshToken)) {
removeAccessToken();
removeRefreshToken();
return config;
}
await reissueAccessTokenApi(refreshToken)
.then((res) => {
accessToken = res.data.accessToken;
saveAccessToken(accessToken);
})
.catch((err) => {
removeAccessToken();
removeRefreshToken();
console.error("인증 토큰 갱신중 오류가 발생했습니다", err);
});
}
if (accessToken !== null) {
newConfig.headers.Authorization = convertToBearer(accessToken);
}
return newConfig;
},
(error) => Promise.reject(error),
);
axiosInstance.interceptors.response.use(
(response) => response,
async (error) => {
const newError = { ...error };
if (error.response?.status === 401 || error.response?.status === 403) {
const refreshToken = loadRefreshToken();
if (refreshToken === null || isTokenExpired(refreshToken)) {
removeAccessToken();
removeRefreshToken();
throw newError;
}
try {
const newAccessToken = await reissueAccessTokenApi(refreshToken).then((res) => res.data.accessToken);
saveAccessToken(newAccessToken);
if (error?.config.headers === undefined) {
newError.config.headers = {};
}
newError.config.headers.Authorization = convertToBearer(newAccessToken);
return await axios.request(newError.config);
} catch (_err) {
removeAccessToken();
removeRefreshToken();
throw Error("로그인이 필요합니다");
}
} else {
throw newError;
}
},
);
export const publicAxiosInstance: AxiosInstance = axios.create({
baseURL: API_SERVER_URL,
});