This repository has been archived by the owner on Apr 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.ts
182 lines (176 loc) · 5.23 KB
/
request.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
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
import axios from 'axios';
import { ElMessageBox, ElNotification, ElMessage } from 'element-plus';
import qs from 'query-string';
import { QueryClient, QueryCache, MutationCache } from 'vue-query';
import { Headers } from '@/constants';
import router from '@/router';
import { getToken, setToken } from './storage';
import type { VueQueryPluginOptions } from 'vue-query';
const reSignInCodes = new Set(['LOGIN_REQUIRED', 'LOGIN_TOKEN_INVALID', 'LOGIN_SESSION_EXPIRED']);
const instance = axios.create({
baseURL: process.env.VITE_REQUEST_BASE_URL || 'https://jsonplaceholder.typicode.com/todos/',
timeout: 30_000,
headers: {
...Headers,
},
paramsSerializer: (params: Record<string, any>) =>
qs.stringify(
Object.fromEntries(
Object.entries(params).filter(
([, v]) => !['', 'undefined', 'null', undefined, null].includes(v?.toString() ?? v),
),
),
),
});
instance.interceptors.request.use((config) => ({
...config,
headers: {
...config.headers,
token: getToken(),
'X-Token': getToken(),
'X-Access-Token': getToken(),
},
}));
export { instance as axiosInstance };
export const showError = (
error: IResponseError,
type: 'alert' | 'notification' | 'message' = 'alert',
) => {
const contents = [];
const code =
error?.code ??
error?.response?.data?.code ??
// @ts-ignore
error?.response?.code ??
error?.response?.status ??
'';
if (code) {
contents.push(`错误代码:${code}`);
}
// @ts-ignore
const url = error?.url ?? error?.config?.url ?? error?.request?.url ?? '';
if (url) {
contents.push(`请求地址:${url}`);
}
const message =
error?.message ?? error?.response?.data?.message ?? error?.response?.data?.msg ?? '';
if (message) {
contents.push(`错误信息:${message}`);
}
const content = contents.length <= 1 ? contents[0].split(':')[1] : `${contents.join(',')}。`;
if (type === 'alert') {
ElMessageBox.alert(content, {
title: '错误',
type: 'error',
});
return;
}
if (type === 'notification') {
ElNotification.error({
title: '错误',
message: content,
});
return;
}
if (type === 'message') {
ElMessage.error({
message: content,
});
}
};
export const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: (error) => {
showError(error as IResponseError);
},
}),
mutationCache: new MutationCache({
onError: (error) => {
showError(error as IResponseError);
},
}),
defaultOptions: {
queries: {
queryFn: async ({ queryKey }) => {
// console.log('');
// console.log('queryKey', queryKey);
// console.log('');
const urlParams = Array.isArray(queryKey[1]) ? queryKey[1] : [];
let url = (queryKey[0] as any).toString() as string;
for (const [idx, param] of urlParams.entries()) {
url = url.replace(`:${idx}`, param.toString() as string);
}
const params = queryKey[2] as Record<string, any>;
const config = queryKey[3] as IRequestConfig;
const { data } = await instance.request<IResponseData>({
method: 'GET',
url,
params,
...config,
});
if (!(data?.success ?? true)) {
if (reSignInCodes.has(data.code)) {
setToken();
showError({
message: '请重新登录。',
} as IResponseError);
router.push({
path: '/sign-in',
query: {
redirect: encodeURIComponent(router.currentRoute.value.fullPath),
},
});
} else if (config?.showError ?? true) {
showError(data as unknown as IResponseError, config?.showErrorType);
}
}
return data;
},
refetchOnWindowFocus: false,
retry: (failureCount, error) => {
if ([403, 404, 500].includes((error as IResponseError).response?.status ?? 200)) {
return false;
}
return failureCount < 3;
},
},
mutations: {
mutationFn: async (variables) => {
// console.log('');
// console.log('variables', variables);
// console.log('');
const config = { ...(variables as IRequestConfig) };
const { data } = await instance.request<IResponseData>({
method: 'POST',
...config,
});
if (!(data?.success ?? true)) {
if (reSignInCodes.has(data.code)) {
setToken();
showError({
message: '请重新登录。',
} as IResponseError);
router.push({
path: '/sign-in',
query: {
redirect: encodeURIComponent(router.currentRoute.value.fullPath),
},
});
} else if (config?.showError ?? true) {
showError(data as unknown as IResponseError, config?.showErrorType);
}
}
return data;
},
retry: (failureCount, error) => {
if ([403, 404, 500].includes((error as IResponseError).response?.status ?? 200)) {
return false;
}
return failureCount < 3;
},
},
},
});
export const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClient,
};