import { IRequestOptions } from '@ysfe/request/src/intf/IRequestOptions' const listen = { count: 0, last: false } /** 处理请求 loading */ export const loading = () => { return function (_target: any, _methodName: any, desc: any) { // 1. 保存当前的方法 const oMethod = desc.value // 2. 改写方法 desc.value = async function (req: IRequestOptions) { let { loading, loadingContext } = req ?? {} let timer: any = null let tips: string | null = null let noDelay: boolean = false if (!loading || !loading.delayTime) return await oMethod.apply(this, [req]) if (loadingContext) { if (typeof loadingContext === 'string') { tips = loadingContext } else { tips = loadingContext.message noDelay = !!loadingContext.noDelay } } try { listen.count++ // ? 增加对自定义loading状态判断 if (!noDelay) { // ? 创建 setTimeout, 当倒计时结束前还在执行请求, 触发loading timer = setTimeout(() => { if (listen.count > 0 && !listen.last) { listen.last = true loading?.handler(true, tips ?? undefined) } }, loading.delayTime) } else { if (listen.count > 0 && !listen.last) { listen.last = true loading?.handler(true, tips ?? undefined) } } return await oMethod.apply(this, [req]) } finally { clearTimeout(timer) listen.count-- if (listen.count <= 0 && listen.last) { listen.count = 0 listen.last = false loading.handler(false) } } } } }