forked from YJU-OKURA/project_minori-next-deployment-repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapiUtils.ts
81 lines (69 loc) · 2.05 KB
/
apiUtils.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
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
import BASE_URLS from './baseUrl';
import HTTP_STATUS from './httpStatus';
async function fetchWithInterceptors(url: string, options: RequestInit) {
let response = await fetch(url, options);
if (response.status === 401) {
const refreshToken = localStorage.getItem('refresh_token');
const refreshResponse = await fetch(
`${BASE_URLS.gin}/auth/google/refresh-token`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({refresh_token: refreshToken}),
}
);
if (refreshResponse.ok) {
const data = await refreshResponse.json();
const newToken = data.data.access_token;
localStorage.setItem('access_token', newToken);
options.headers = {
...options.headers,
Authorization: `Bearer ${newToken}`,
};
response = await fetch(url, options);
} else {
console.error('トークンの有効期限が切れました。');
window.location.href = '/';
}
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response;
}
const req = async (
url: string,
method: RequestInit['method'],
server: 'gin' | 'nest',
body: BodyInit | object | undefined = undefined
) => {
const headers = new Headers();
const token = localStorage.getItem('access_token');
if (token) {
headers.append('Authorization', `Bearer ${token}`);
}
if (body instanceof FormData) {
headers.append('Content-Type', 'multipart/form-data');
} else if (body) {
headers.append('Content-Type', 'application/json');
body = JSON.stringify(body);
}
try {
const response = await fetchWithInterceptors(BASE_URLS[server] + url, {
method,
headers,
body,
credentials: 'include',
});
if (response.status === HTTP_STATUS.NO_CONTENT) {
return {};
}
return response.json();
} catch (error) {
console.error(`${method} リクエスト中にエラーが発生しました。`, error);
throw error;
}
};
export default req;