axios-miniprogram/src/core/dispatchRequest.ts

57 lines
1.8 KiB
TypeScript
Raw Normal View History

import { isFunction, isString } from '../helpers/isTypes';
2023-04-09 21:01:43 +08:00
import { assert } from '../helpers/error';
2023-04-10 22:53:15 +08:00
import { Cancel, isCancel, isCancelToken } from './cancel';
2023-03-23 20:09:00 +08:00
import { flattenHeaders } from './flattenHeaders';
import { AxiosTransformer, transformData } from './transformData';
import { request, withDataRE } from './request';
2023-03-23 20:09:00 +08:00
import { AxiosRequestConfig, AxiosResponse } from './Axios';
import { transformURL } from './transformURL';
2023-04-10 22:53:15 +08:00
import { AxiosErrorResponse } 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
2023-04-09 21:01:43 +08:00
assert(isFunction(config.adapter), 'adapter 不是一个 function');
assert(isString(config.url), 'url 不是一个 string');
assert(isString(config.method), 'method 不是一个 string');
2023-03-23 20:09:00 +08:00
config.url = transformURL(config);
config.headers = flattenHeaders(config);
if (withDataRE.test(config.method!)) {
transformer(config, config.transformRequest);
}
2023-04-09 15:20:10 +08:00
function onSuccess(response: AxiosResponse) {
throwIfCancellationRequested(config);
transformer(response, config.transformResponse);
return response;
2023-04-03 21:03:33 +08:00
}
2023-03-23 20:09:00 +08:00
2023-04-10 22:53:15 +08:00
function onError(reason: Cancel | AxiosErrorResponse) {
if (!isCancel(reason)) {
2023-04-03 21:03:33 +08:00
throwIfCancellationRequested(config);
transformer(reason.response, config.transformResponse);
}
return Promise.reject(reason);
}
2023-04-09 15:20:10 +08:00
function transformer<TData = unknown>(
target: { data?: TData; headers?: AnyObject },
fn?: AxiosTransformer<TData>,
) {
target.data = transformData(target.data, target.headers, fn);
}
return request(config).then(onSuccess, onError);
2023-03-23 20:09:00 +08:00
}