// 兼容以前的老项目写法 import { addPendingRequest, checkIfHasPendingRequest, clearPendingRequest, getCachedRequest, } from './duplicateRequestPrevent' import { normalizeConfig } from './helpers' import { generateRequestHash } from './utils' import type { AjaxInstance, AjaxOption, AnyObj, AxiosMethods } from './types' export type OldAjaxMethods = 'query' | 'create' | 'deletes' | 'putWay' | 'patchWay' export type CustomAjaxMethods = ( path: string, config?: Partial ) => (data?: any, expend?: string, config?: AjaxOption) => Promise type MethodMap = { [k in OldAjaxMethods]: AxiosMethods } const methodMap: MethodMap = { query: 'GET', create: 'POST', putWay: 'PUT', deletes: 'DELETE', patchWay: 'PATCH', } export const generateCustomMethod = (ctx: AjaxInstance, name: OldAjaxMethods): CustomAjaxMethods => (path: string, config: Partial = {}) => async (data?: any, expand?: string, _config?: AjaxOption) => { const url = expand ? `${path}/${expand}` : path if (expand) { console.warn( `业务代码中拼接url发送请求的方式即将废弃,请使用ajax.${methodMap[name].toLocaleLowerCase()}接口替换。相关url:${url}` ) } const [newParams, newData] = methodMap[name] === 'GET' ? [data, undefined] : [undefined, data] const config1 = normalizeConfig(ctx, { ...config, ...(_config ?? {}), url, params: newParams, data: newData, method: methodMap[name], }) const options = { ...config1, custom: { ...ctx.$options, ...config1, }, } const hashKey = generateRequestHash(config1) if (checkIfHasPendingRequest(hashKey)) { // 重复,且处于pending状态的请求,复用 return getCachedRequest(hashKey) } const request = ctx.request(options) // 缓存请求 addPendingRequest(hashKey, request, options.reUseDuration) try { return await request } finally { // 清理缓存的请求 clearPendingRequest(hashKey) } } function addCompatibleMethods>(ctx: AjaxInstance) { ctx.query = generateCustomMethod(ctx, 'query') ctx.create = generateCustomMethod(ctx, 'create') ctx.deletes = generateCustomMethod(ctx, 'deletes') ctx.putWay = generateCustomMethod(ctx, 'putWay') ctx.patchWay = generateCustomMethod(ctx, 'patchWay') } export default addCompatibleMethods