forked from chaitin/MonkeyCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpClient.ts
More file actions
229 lines (207 loc) · 6.33 KB
/
httpClient.ts
File metadata and controls
229 lines (207 loc) · 6.33 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
/* eslint-disable */
/* tslint:disable */
// @ts-nocheck
/*
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
* ## ##
* ## AUTHOR: acacode ##
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
* ---------------------------------------------------------------
*/
import { message as Message } from '@ctzhian/ui';
import type {
AxiosInstance,
AxiosRequestConfig,
HeadersDefaults,
ResponseType,
} from 'axios';
import axios from 'axios';
export type QueryParamsType = Record<string | number, any>;
export interface FullRequestParams
extends Omit<AxiosRequestConfig, 'data' | 'params' | 'url' | 'responseType'> {
/** set parameter to `true` for call `securityWorker` for this request */
secure?: boolean;
/** request path */
path: string;
/** content type of request body */
type?: ContentType;
/** query params */
query?: QueryParamsType;
/** format of response (i.e. response.json() -> format: "json") */
format?: ResponseType;
/** request body */
body?: unknown;
}
export type RequestParams = Omit<
FullRequestParams,
'body' | 'method' | 'query' | 'path'
>;
export interface ApiConfig<SecurityDataType = unknown>
extends Omit<AxiosRequestConfig, 'data' | 'cancelToken'> {
securityWorker?: (
securityData: SecurityDataType | null
) => Promise<AxiosRequestConfig | void> | AxiosRequestConfig | void;
secure?: boolean;
format?: ResponseType;
}
export enum ContentType {
Json = 'application/json',
FormData = 'multipart/form-data',
UrlEncoded = 'application/x-www-form-urlencoded',
Text = 'text/plain',
}
const whitePathnameList = ['/user/login', '/login', '/auth', '/invite'];
const whiteApiList = ['/api/v1/user/profile', '/api/v1/admin/profile'];
const redirectToLogin = () => {
const redirectAfterLogin = encodeURIComponent(location.href);
const search = `redirect=${redirectAfterLogin}`;
const pathname = location.pathname.startsWith('/user')
? '/login'
: '/login/admin';
window.location.href = `${pathname}`;
};
type ExtractDataProp<T> = T extends { data?: infer U } ? U : never;
export class HttpClient<SecurityDataType = unknown> {
public instance: AxiosInstance;
private securityData: SecurityDataType | null = null;
private securityWorker?: ApiConfig<SecurityDataType>['securityWorker'];
private secure?: boolean;
private format?: ResponseType;
constructor({
securityWorker,
secure,
format,
...axiosConfig
}: ApiConfig<SecurityDataType> = {}) {
this.instance = axios.create({
withCredentials: true,
...axiosConfig,
baseURL: axiosConfig.baseURL || '',
});
this.secure = secure;
this.format = format;
this.securityWorker = securityWorker;
this.instance.interceptors.response.use(
(resp) => {
if (resp.data.code === 0) {
return resp.data.data;
} else {
Message.error(resp.data.message);
return Promise.reject(resp.data.message);
}
},
(err) => {
if (err?.response?.status === 401) {
if (
whitePathnameList.find((item) => location.pathname.startsWith(item))
) {
return Promise.reject('尚未登录');
}
Message.error('尚未登录');
redirectToLogin();
return Promise.reject('尚未登录');
}
// 手动取消请求
if (err.code === 'ERR_CANCELED') {
return;
}
const msg = err?.response?.data?.message || err?.message;
Message.error(msg);
return Promise.reject(msg);
}
);
}
public setSecurityData = (data: SecurityDataType | null) => {
this.securityData = data;
};
protected mergeRequestParams(
params1: AxiosRequestConfig,
params2?: AxiosRequestConfig
): AxiosRequestConfig {
const method = params1.method || (params2 && params2.method);
return {
...this.instance.defaults,
...params1,
...(params2 || {}),
headers: {
...((method &&
this.instance.defaults.headers[
method.toLowerCase() as keyof HeadersDefaults
]) ||
{}),
...(params1.headers || {}),
...((params2 && params2.headers) || {}),
},
};
}
protected stringifyFormItem(formItem: unknown) {
if (typeof formItem === 'object' && formItem !== null) {
return JSON.stringify(formItem);
} else {
return `${formItem}`;
}
}
protected createFormData(input: Record<string, unknown>): FormData {
return Object.keys(input || {}).reduce((formData, key) => {
const property = input[key];
const propertyContent: any[] =
property instanceof Array ? property : [property];
for (const formItem of propertyContent) {
const isFileType = formItem instanceof Blob || formItem instanceof File;
formData.append(
key,
isFileType ? formItem : this.stringifyFormItem(formItem)
);
}
return formData;
}, new FormData());
}
public request = async <T = any, _E = any>({
secure,
path,
type,
query,
format,
body,
...params
}: FullRequestParams): Promise<ExtractDataProp<T>> => {
const secureParams =
((typeof secure === 'boolean' ? secure : this.secure) &&
this.securityWorker &&
(await this.securityWorker(this.securityData))) ||
{};
const requestParams = this.mergeRequestParams(params, secureParams);
const responseFormat = format || this.format || undefined;
if (
type === ContentType.FormData &&
body &&
body !== null &&
typeof body === 'object'
) {
body = this.createFormData(body as Record<string, unknown>);
}
if (
type === ContentType.Text &&
body &&
body !== null &&
typeof body !== 'string'
) {
body = JSON.stringify(body);
}
return this.instance.request({
...requestParams,
headers: {
...(requestParams.headers || {}),
...(type && type !== ContentType.FormData
? { 'Content-Type': type }
: {}),
},
params: query,
responseType: responseFormat,
data: body,
url: path,
});
};
}
export default new HttpClient({ format: 'json' }).request;