axios-miniprogram/src/request/dispatchRequest.ts

67 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-05-04 10:39:52 +08:00
import { WITH_DATA_RE } from '../constants/methods'
import { isFunction, isString } from '../helpers/isTypes'
import { assert } from '../helpers/error'
import { AxiosRequestConfig, AxiosResponse } from '../core/Axios'
import { Cancel, isCancel, isCancelToken } from './cancel'
import { flattenHeaders } from './flattenHeaders'
import { AxiosTransformer, transformData } from './transformData'
import { request } from './request'
import { AxiosErrorResponse } from './createError'
2023-03-23 20:09:00 +08:00
/**
*
*
*
*
* @param config
*/
2023-04-09 15:20:10 +08:00
export function dispatchRequest(config: AxiosRequestConfig) {
2023-05-04 10:39:52 +08:00
throwIfCancellationRequested(config)
2023-04-09 15:20:10 +08:00
2023-05-04 10:39:52 +08:00
assert(isFunction(config.adapter), 'adapter 不是一个 function')
assert(isString(config.url), 'url 不是一个 string')
assert(isString(config.method), 'method 不是一个 string')
2023-04-09 21:01:43 +08:00
2023-05-04 10:39:52 +08:00
config.headers = flattenHeaders(config)
2023-05-04 10:39:52 +08:00
// 可以携带 data 的请求方法,转换 data
// 否则,删除 data
if (WITH_DATA_RE.test(config.method!)) {
dataTransformer(config, config.transformRequest)
} else {
delete config.data
}
2023-05-04 10:39:52 +08:00
function onSuccess(response: AxiosResponse) {
throwIfCancellationRequested(config)
dataTransformer(response, config.transformResponse)
2023-05-04 10:39:52 +08:00
return response
}
2023-03-23 20:09:00 +08:00
2023-05-04 10:39:52 +08:00
function onError(error: Cancel | AxiosErrorResponse) {
if (!isCancel(error)) {
throwIfCancellationRequested(config)
dataTransformer(error.response, config.transformResponse)
}
2023-05-04 10:39:52 +08:00
return Promise.reject(error)
}
2023-05-04 10:39:52 +08:00
function dataTransformer<TData = unknown>(
obj: { data?: TData; headers?: AnyObject },
fn?: AxiosTransformer<TData>,
) {
obj.data = transformData(obj.data, obj.headers, fn)
}
2023-05-04 10:39:52 +08:00
return request(config).then(onSuccess, onError)
2023-03-23 20:09:00 +08:00
}
function throwIfCancellationRequested(config: AxiosRequestConfig) {
2023-05-04 10:39:52 +08:00
const { cancelToken } = config
if (isCancelToken(cancelToken)) {
cancelToken.throwIfRequested()
}
}