-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathapi.ts
More file actions
284 lines (246 loc) · 7.22 KB
/
Copy pathapi.ts
File metadata and controls
284 lines (246 loc) · 7.22 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import Cookies from 'js-cookie';
import { useAuthStore } from '@/lib/stores/auth-store';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL;
if (!API_BASE_URL) {
throw new Error('NEXT_PUBLIC_API_URL environment variable is not defined');
}
export interface ApiResponse<T = unknown> {
data: T;
status: number;
statusText: string;
}
export interface ApiError {
message: string;
status: number;
code?: string;
}
export interface RequestConfig {
headers?: Record<string, string>;
timeout?: number;
skipAuthRefresh?: boolean;
}
// Token refresh function
const refreshAccessToken = async (): Promise<string | null> => {
try {
const refreshToken = Cookies.get('refreshToken');
if (!refreshToken) {
return null;
}
const response = await axios.post(
`${API_BASE_URL}/auth/refresh`,
{ refreshToken },
{
headers: {
'Content-Type': 'application/json',
},
}
);
const { accessToken, refreshToken: newRefreshToken } = response.data.data;
// Update tokens in store and cookies
const authStore = useAuthStore.getState();
authStore.setTokens(accessToken, newRefreshToken);
return accessToken;
} catch {
// If refresh fails, clear auth data
const authStore = useAuthStore.getState();
authStore.clearAuth();
return null;
}
};
const createClientApi = (): AxiosInstance => {
const instance = axios.create({
baseURL: API_BASE_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
withCredentials: true,
});
// Request interceptor
instance.interceptors.request.use(
config => {
config.withCredentials = true;
const accessToken = Cookies.get('accessToken');
if (accessToken && !config.headers?.Authorization) {
config.headers = config.headers || {};
config.headers.Authorization = `Bearer ${accessToken}`;
}
return config;
},
error => {
return Promise.reject(error);
}
);
// Response interceptor with automatic token refresh
instance.interceptors.response.use(
(response: AxiosResponse) => {
return response;
},
async error => {
const originalRequest = error.config;
// Handle 401 errors with automatic token refresh
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
// Skip auth refresh if explicitly requested
if (originalRequest.skipAuthRefresh) {
const authStore = useAuthStore.getState();
authStore.clearAuth();
return Promise.reject({
message: 'Authentication required',
status: 401,
code: 'UNAUTHORIZED',
});
}
try {
const newAccessToken = await refreshAccessToken();
if (newAccessToken) {
// Retry the original request with new token
originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
return instance(originalRequest);
} else {
// Refresh failed, redirect to login
const authStore = useAuthStore.getState();
authStore.clearAuth();
// Only redirect if we're on the client side
if (typeof window !== 'undefined') {
window.location.href = '/auth/signin';
}
return Promise.reject({
message: 'Session expired. Please login again.',
status: 401,
code: 'SESSION_EXPIRED',
});
}
} catch {
const authStore = useAuthStore.getState();
authStore.clearAuth();
// Only redirect if we're on the client side
if (typeof window !== 'undefined') {
window.location.href = '/auth/signin';
}
return Promise.reject({
message: 'Session expired. Please login again.',
status: 401,
code: 'SESSION_EXPIRED',
});
}
}
// Handle other errors
if (error.response) {
const errorData = error.response.data;
const customError: ApiError = {
message:
errorData?.message ||
`HTTP error! status: ${error.response.status}`,
status: error.response.status,
code: errorData?.code,
};
return Promise.reject(customError);
} else if (error.request) {
return Promise.reject(new Error('Network error: No response received'));
} else {
return Promise.reject(new Error(`Request error: ${error.message}`));
}
}
);
return instance;
};
const axiosInstance = createClientApi();
const convertAxiosResponse = <T>(
response: AxiosResponse<T>
): ApiResponse<T> => ({
data: response.data,
status: response.status,
statusText: response.statusText,
});
const convertRequestConfig = (config?: RequestConfig): AxiosRequestConfig => ({
headers: config?.headers,
timeout: config?.timeout,
withCredentials: true,
});
const clientApi = {
get: async <T = unknown>(
url: string,
config?: RequestConfig
): Promise<ApiResponse<T>> => {
const response = await axiosInstance.get<T>(
url,
convertRequestConfig(config)
);
return convertAxiosResponse(response);
},
post: async <T = unknown>(
url: string,
data?: unknown,
config?: RequestConfig
): Promise<ApiResponse<T>> => {
const response = await axiosInstance.post<T>(
url,
data,
convertRequestConfig(config)
);
return convertAxiosResponse(response);
},
put: async <T = unknown>(
url: string,
data?: unknown,
config?: RequestConfig
): Promise<ApiResponse<T>> => {
const response = await axiosInstance.put<T>(
url,
data,
convertRequestConfig(config)
);
return convertAxiosResponse(response);
},
patch: async <T = unknown>(
url: string,
data?: unknown,
config?: RequestConfig
): Promise<ApiResponse<T>> => {
const response = await axiosInstance.patch<T>(
url,
data,
convertRequestConfig(config)
);
return convertAxiosResponse(response);
},
delete: async <T = unknown>(
url: string,
config?: RequestConfig
): Promise<ApiResponse<T>> => {
const response = await axiosInstance.delete<T>(
url,
convertRequestConfig(config)
);
return convertAxiosResponse(response);
},
};
export const api = {
get: <T = unknown>(
url: string,
config?: RequestConfig
): Promise<ApiResponse<T>> => clientApi.get<T>(url, config),
post: <T = unknown>(
url: string,
data?: unknown,
config?: RequestConfig
): Promise<ApiResponse<T>> => clientApi.post<T>(url, data, config),
put: <T = unknown>(
url: string,
data?: unknown,
config?: RequestConfig
): Promise<ApiResponse<T>> => clientApi.put<T>(url, data, config),
patch: <T = unknown>(
url: string,
data?: unknown,
config?: RequestConfig
): Promise<ApiResponse<T>> => clientApi.patch<T>(url, data, config),
delete: <T = unknown>(
url: string,
config?: RequestConfig
): Promise<ApiResponse<T>> => clientApi.delete<T>(url, config),
};
export default axiosInstance;