axios-miniprogram/src/core/dispatchRequest.ts

64 lines
1.7 KiB
TypeScript
Raw Normal View History

import { isFunction } 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 { AxiosTransformer, transformData } from './transformData';
2023-03-23 20:09:00 +08:00
import { request } from './request';
import { AxiosRequestConfig, AxiosResponse } from './Axios';
import { transformURL } from './transformURL';
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
}
}
2023-04-09 15:20:10 +08:00
export function dispatchRequest(config: AxiosRequestConfig) {
2023-03-23 20:09:00 +08:00
throwIfCancellationRequested(config);
2023-04-09 15:20:10 +08:00
const { transformRequest, transformResponse } = config;
2023-03-23 20:09:00 +08:00
config.url = transformURL(config);
config.method = config.method ?? 'get';
2023-03-23 20:09:00 +08:00
config.headers = flattenHeaders(config);
2023-04-09 15:20:10 +08:00
transformer(config, transformRequest);
2023-04-09 15:20:10 +08:00
function onSuccess(response: AxiosResponse) {
throwIfCancellationRequested(config);
2023-04-09 15:20:10 +08:00
transformer(response, transformResponse);
return response;
2023-04-03 21:03:33 +08:00
}
2023-03-23 20:09:00 +08:00
function onError(reason: unknown) {
if (!isCancel(reason)) {
2023-04-03 21:03:33 +08:00
throwIfCancellationRequested(config);
2023-04-09 15:20:10 +08:00
if (isAxiosError(reason)) {
2023-04-09 15:20:10 +08:00
transformer(reason.response as AxiosResponse, transformResponse);
2023-03-23 20:09:00 +08:00
}
}
if (isFunction(config.errorHandler)) {
return config.errorHandler(reason);
}
return Promise.reject(reason);
}
2023-04-09 15:20:10 +08:00
function transformer<TData = unknown>(
targetObject: { data?: TData; headers?: AnyObject },
transformer?: AxiosTransformer<TData>,
) {
2023-04-09 15:20:10 +08:00
targetObject.data = transformData(
targetObject.data,
targetObject.headers,
transformer,
2023-04-09 15:20:10 +08:00
);
}
2023-04-09 15:20:10 +08:00
return request(config).then(onSuccess).catch(onError);
2023-03-23 20:09:00 +08:00
}