2023-03-28 21:32:54 +08:00
|
|
|
import { isPlainObject } from '../helpers/isTypes';
|
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';
|
|
|
|
|
|
|
|
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,
|
|
|
|
);
|
|
|
|
|
|
|
|
return request<TData>(config).then(
|
|
|
|
(response: AxiosResponse<TData>) => {
|
|
|
|
throwIfCancellationRequested(config);
|
|
|
|
|
|
|
|
response.data = transformData(
|
|
|
|
response.data as AnyObject,
|
|
|
|
response.headers,
|
|
|
|
config.transformResponse,
|
|
|
|
) as TData;
|
|
|
|
|
|
|
|
return response;
|
|
|
|
},
|
|
|
|
(reason: unknown) => {
|
|
|
|
if (!isCancel(reason)) {
|
|
|
|
throwIfCancellationRequested(config);
|
|
|
|
|
|
|
|
if (isPlainObject(reason) && isPlainObject(reason.response)) {
|
|
|
|
reason.response.data = transformData(
|
|
|
|
reason.response.data,
|
|
|
|
reason.response.headers,
|
|
|
|
config.transformResponse,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
throw config.errorHandler?.(reason) ?? reason;
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|