-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
api.ts
115 lines (93 loc) · 3.1 KB
/
api.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
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
import { logout, LogoutReason, refresh } from '@/auth';
import { useRequestsStore } from '@/stores/';
import { getRootPath } from '@/utils/get-root-path';
import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import { addQueryToPath } from './utils/add-query-to-path';
import PQueue from 'p-queue';
const api = axios.create({
baseURL: getRootPath(),
withCredentials: true,
headers: {
'Cache-Control': 'no-store',
},
});
const queue = new PQueue({ concurrency: 5, intervalCap: 5, interval: 500, carryoverConcurrencyCount: true });
interface RequestConfig extends AxiosRequestConfig {
id: string;
}
interface Response extends AxiosResponse {
config: RequestConfig;
}
export interface RequestError extends AxiosError {
response: Response;
}
export const onRequest = (config: AxiosRequestConfig): Promise<RequestConfig> => {
const requestsStore = useRequestsStore();
const id = requestsStore.startRequest();
const requestConfig: RequestConfig = {
id: id,
...config,
};
return new Promise((resolve) => {
if (config.url && config.url === '/auth/refresh') {
queue.pause();
resolve(requestConfig);
queue.start();
} else {
queue.add(() => resolve(requestConfig));
}
});
};
export const onResponse = (response: AxiosResponse | Response): AxiosResponse | Response => {
const requestsStore = useRequestsStore();
const id = (response.config as RequestConfig)?.id;
if (id) requestsStore.endRequest(id);
return response;
};
export const onError = async (error: RequestError): Promise<RequestError> => {
const requestsStore = useRequestsStore();
// Note: Cancelled requests don't respond with the config
const id = (error.response?.config as RequestConfig)?.id;
if (id) requestsStore.endRequest(id);
// If a request fails with the unauthorized error, it either means that your user doesn't have
// access, or that your session doesn't exist / has expired.
// In case of the second, we should force the app to logout completely and redirect to the login
// view.
const status = error.response?.status;
const code = error.response?.data?.errors?.[0]?.extensions?.code;
if (
status === 401 &&
code === 'INVALID_CREDENTIALS' &&
error.request.responseURL.includes('refresh') === false &&
error.request.responseURL.includes('login') === false &&
error.request.responseURL.includes('tfa') === false
) {
let newToken: string | undefined;
try {
newToken = await refresh();
} catch {
logout({ reason: LogoutReason.SESSION_EXPIRED });
return Promise.reject();
}
if (newToken) {
return api.request({
...error.config,
headers: {
Authorization: `Bearer ${newToken}`,
},
});
}
}
return Promise.reject(error);
};
api.interceptors.request.use(onRequest);
api.interceptors.response.use(onResponse, onError);
export default api;
export function getToken(): string | null {
return api.defaults.headers.common['Authorization']?.split(' ')[1] || null;
}
export function addTokenToURL(url: string, token?: string): string {
const accessToken = token || getToken();
if (!accessToken) return url;
return addQueryToPath(url, { access_token: accessToken });
}