axios-miniprogram/src/core/dispatchRequest.ts

69 lines
2.1 KiB
TypeScript
Raw Normal View History

import { isFunction, isPromise, 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');
const { errorHandler, transformRequest, transformResponse } = config;
2023-03-23 20:09:00 +08:00
config.url = transformURL(config);
config.headers = flattenHeaders(config);
if (withDataRE.test(config.method!)) {
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
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);
2023-04-10 22:53:15 +08:00
transformer(reason.response, transformResponse);
}
2023-04-09 21:01:43 +08:00
if (isFunction(errorHandler)) {
const promise = errorHandler(reason);
if (isPromise(promise)) {
return promise.then(() => Promise.reject(reason));
2023-04-09 21:01:43 +08:00
}
}
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
}