-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
70 lines (56 loc) · 2.04 KB
/
Copy pathclient.ts
File metadata and controls
70 lines (56 loc) · 2.04 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
import { create, isAxiosError } from 'axios';
import { env } from '@/shared/constants/env';
import { ApiError } from './types';
export const client = create({
baseURL: env.API_BASE_URL,
timeout: 15_000,
headers: { 'Content-Type': 'application/json' },
});
// Lazily imported to avoid circular deps at module load time
type AuthStateAccessor = () => {
accessToken: string | null;
refreshToken: string | null;
setSession: (tokens: { accessToken: string; refreshToken: string }, user: any) => void;
clearSession: () => void;
};
let getAuthState: AuthStateAccessor | null = null;
export function registerAuthStore(store: AuthStateAccessor) {
getAuthState = store;
}
client.interceptors.request.use((config) => {
const token = getAuthState?.().accessToken;
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
client.interceptors.response.use(
(res) => res,
async (error) => {
const original = error.config as typeof error.config & { _retry?: boolean };
if (error.response?.status === 401 && !original._retry && getAuthState) {
original._retry = true;
const { refreshToken, clearSession } = getAuthState();
if (!refreshToken) {
clearSession();
return Promise.reject(toApiError(error));
}
try {
const { authApi } = await import('@/features/auth/api/auth.api');
const newTokens = await authApi.refreshTokens(refreshToken);
getAuthState().setSession(newTokens, getAuthState().accessToken);
original.headers.Authorization = `Bearer ${newTokens.accessToken}`;
return client(original);
} catch {
getAuthState().clearSession();
return Promise.reject(toApiError(error));
}
}
return Promise.reject(toApiError(error));
},
);
function toApiError(error: unknown): ApiError {
if (isAxiosError(error)) {
const msg = (error.response?.data as { message?: string })?.message ?? error.message;
return new ApiError(msg, error.response?.status ?? 0);
}
return new ApiError('Unknown error', 0);
}