2023-04-02 23:27:45 +08:00
|
|
|
import { isCancel, isCancelToken } from './cancel';
|
2023-03-23 20:09:00 +08:00
|
|
|
import { flattenHeaders } from './flattenHeaders';
|
|
|
|
import { transformData } from './transformData';
|
|
|
|
import { request } from './request';
|
|
|
|
import { AxiosRequestConfig, AxiosResponse } from './Axios';
|
|
|
|
import { transformURL } from './transformURL';
|
2023-04-07 12:51:18 +08:00
|
|
|
import { isAxiosError } from './createError';
|
2023-03-23 20:09:00 +08:00
|
|
|
|
|
|
|
function throwIfCancellationRequested(config: AxiosRequestConfig) {
|
2023-04-02 23:27:45 +08:00
|
|
|
const { cancelToken } = config;
|
|
|
|
if (isCancelToken(cancelToken)) {
|
|
|
|
cancelToken.throwIfRequested();
|
2023-03-23 20:09:00 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function dispatchRequest<TData = unknown>(
|
|
|
|
config: AxiosRequestConfig,
|
|
|
|
): Promise<AxiosResponse> {
|
|
|
|
throwIfCancellationRequested(config);
|
|
|
|
|
2023-03-28 20:48:02 +08:00
|
|
|
config.method = config.method ?? 'get';
|
2023-03-23 20:09:00 +08:00
|
|
|
config.url = transformURL(config);
|
|
|
|
config.headers = flattenHeaders(config);
|
|
|
|
config.data = transformData(
|
|
|
|
config.data,
|
|
|
|
config.headers,
|
|
|
|
config.transformRequest,
|
|
|
|
);
|
|
|
|
|
2023-04-03 21:03:33 +08:00
|
|
|
function transformer(response: AxiosResponse<TData>) {
|
|
|
|
response.data = transformData(
|
|
|
|
response.data as AnyObject,
|
|
|
|
response.headers,
|
|
|
|
config.transformResponse,
|
|
|
|
) as TData;
|
|
|
|
}
|
2023-03-23 20:09:00 +08:00
|
|
|
|
2023-04-03 21:03:33 +08:00
|
|
|
return request<TData>(config)
|
|
|
|
.then((response: AxiosResponse<TData>) => {
|
|
|
|
throwIfCancellationRequested(config);
|
|
|
|
transformer(response);
|
2023-03-23 20:09:00 +08:00
|
|
|
return response;
|
2023-04-03 21:03:33 +08:00
|
|
|
})
|
|
|
|
.catch((reason: unknown) => {
|
2023-03-23 20:09:00 +08:00
|
|
|
if (!isCancel(reason)) {
|
|
|
|
throwIfCancellationRequested(config);
|
2023-04-07 12:51:18 +08:00
|
|
|
if (isAxiosError(reason)) {
|
|
|
|
transformer(reason.response as AxiosResponse<TData>);
|
2023-03-23 20:09:00 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
throw config.errorHandler?.(reason) ?? reason;
|
2023-04-03 21:03:33 +08:00
|
|
|
});
|
2023-03-23 20:09:00 +08:00
|
|
|
}
|