-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbase.ts
More file actions
121 lines (101 loc) · 3.47 KB
/
base.ts
File metadata and controls
121 lines (101 loc) · 3.47 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import { webPath } from '@router/index';
const baseURL = import.meta.env.VITE_BASE_URL;
const Headers = { 'Content-Type': 'application/json' } as const;
const wait = (timeToDelay: number) => new Promise((resolve) => setTimeout(resolve, timeToDelay));
const enableMock = false;
const fetchData = async (path: string, init: RequestInit = {}, isFormData: boolean = false) => {
try {
const url = `${baseURL}${path}`;
const res = await fetch(url, {
method: 'GET',
...init,
headers: {
...(isFormData ? {} : Headers),
...init.headers,
},
});
const data = await res.json();
if (data.state) return data;
if (!res.ok) {
throw new Error(`${res.status} Error!!`);
}
await wait(0);
return data;
} catch (error) {
throw error;
}
};
const fetchAuthData = async (path: string, init: RequestInit = {}, isFormData: boolean = false) => {
try {
const url = `${baseURL}${path}`;
const token = localStorage.getItem('access_token');
let res = await fetch(url, {
method: 'GET',
...init,
headers: {
...(isFormData ? {} : Headers),
...(init.headers as any),
Authorization: `Bearer ${token}`,
},
credentials: 'include', // 쿠키 포함
});
if (res.status === 401) {
const refreshToken = localStorage.getItem('refresh_token');
const reissueRes = await fetch(`${baseURL}/auth/reissue`, {
method: 'POST',
headers: {
...Headers,
},
body: JSON.stringify({
refreshToken: refreshToken,
}),
});
if (!reissueRes.ok) {
alert('토큰 재발급 실패. 재로그인 필요');
window.location.href = webPath.login();
throw new Error('토큰 재발급 실패. 재로그인 필요');
}
const { access_token, refresh_token: newRefreshToken } = await reissueRes.json();
// 새 토큰 저장
localStorage.setItem('access_token', access_token);
localStorage.setItem('refresh_token', newRefreshToken);
// localStorage 변경을 React state에 반영하기 위한 커스텀 이벤트 발생
window.dispatchEvent(new CustomEvent('localStorageChange', { detail: { key: 'access_token' } }));
window.dispatchEvent(new CustomEvent('localStorageChange', { detail: { key: 'refresh_token' } }));
(window as any).ReactNativeWebView?.postMessage(JSON.stringify({ type: 'TOKEN', token: access_token }));
// const token = localStorage.getItem('access_token');
// if (token && window.ReactNativeWebView) {
// window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'TOKEN', token }));
// }
// 원래 요청 재시도
res = await fetch(url, {
method: 'GET',
...init,
headers: {
...Headers,
...(init.headers as any),
Authorization: `Bearer ${access_token}`,
},
credentials: 'include',
});
}
if (!res.ok) {
throw new Error(`${res.status} Error!!`);
}
await wait(0);
// 204 No Content 응답 처리
if (res.status === 204) {
return null;
}
const data = await res.json();
return data;
} catch (error) {
throw error;
}
};
// function getCookie(name: string) {
// const value = `; ${document.cookie}`;
// const parts = value.split(`; ${name}=`);
// if (parts.length === 2) return parts.pop()?.split(';').shift();
// }
export { baseURL, Headers, wait, enableMock, fetchData, fetchAuthData };