MergeApi装饰器方案

DONG HAO
2023-02-09 / 0 评论 / 198 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年02月09日,已超过441天没有更新,若内容或图片失效,请留言反馈。
定义一个接口可以入参数组
当一个时间内的不同调用参数形成多个Api请求时候,可以合并请求,使用下面的合并请求装饰器

装饰器

import { mergeWith, isArray, unionWith, isEqual } from 'lodash'

/**
 * log
 * @param type log类型
 * @param id logId
 * @param input 输入
 * @param pending 延时
 */
function log(id: string, input: any, pending?: number) {
    console.group('%c%s(%s)', 'color:#0764E9;padding:2px;', '[MergeApi]', id)
    console.log('%c延时:', 'color:green;padding:2px;', `${pending} ms`)
    console.log('%c参数:', 'color:green;padding:2px;', input)
    console.groupEnd();
}

export interface MergeApiConfig {
    delay?: number,
    debug?: boolean,
}

/**
 * 合并接口调用
 * @param config 配置
 * @returns
 */
export function MergeApi(config?: MergeApiConfig) {
    let cache: object = {};
    let timer: number | null = null;
    let promise: Promise<any> = Promise.resolve();

    return function(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) {
        const { delay = 500, debug = false, } = config || {}

        const key = `${target.name}.${propertyKey}`
        const method = descriptor.value;

        descriptor.value = function(arg: object = {}) {
            const input = JSON.parse(JSON.stringify(arg))
            mergeWith(cache, input, (obj, src) => {
                if (isArray(obj)) {
                    return unionWith(obj, src, isEqual);
                }
            })

            if (timer) {
                return promise
            }

            promise = new Promise((resolve, reject) => {
                timer = window.setTimeout(() => {
                    debug && log(key, cache, delay)
                    method.apply(this, [cache])
                        .then(resolve)
                        .catch(reject)
                    clearTimeout(timer as number)
                    timer = null
                    cache = {}
                }, delay)
            })
            return promise;
        }
        return descriptor
    }
}

使用

export class ApiTranslate {
    @MergeApi({ delay: 800, })
    static translate(args) {
        return Promise...
    }
}
0

评论 (0)

取消