网站搜索

类 - Typescript | 每次调用函数时调用另一个函数


我正在尝试编写一个 Typescript API 服务。对于该服务,我需要一种方法来检查当调用诸如 get 这样的函数时,该方法是否存在。

我意识到我可以这样做

get(endpoint: string) {
    this.handleRequest();
}

post(endpoint: string, data: any) {
    this.handleRequest();
}

但是我并不特别想在每种方法的顶部做那件事,所以我不知道是否有办法在 Typescript 类的构造函数中监听子函数的调用。

能够做到这一点似乎有点牵强,但在像我这样的情况下会非常有用,这样我就不必一直去做它了。

export class ApiService {
    base_url: string = 'https://jsonplaceholder.typicode.com/posts';
    methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];

    /**
     * Create an instance of ApiService.
     * @param {string} base_url
     */
    constructor(base_url: string = null) {
        this.base_url = base_url ? base_url : this.base_url;
    }

    get(endpoint: string): string {
        // duplicated line
        this.handleRequest();

        return 'get method';
    }

    post(endpoint: string, data: any): string {
        // duplicated line
        this.handleRequest();

        return 'post method';
    }

    protected handleRequest(): string {
        return 'handle the request';
    }
}

答案#1

你可以使用一个装饰器来实现这一点,该装饰器会用一个调用原始实现和你额外方法的方法来重写类的所有方法:

function handleRequest() {
    return function<TFunction extends Function>(target: TFunction){
        for(let prop of Object.getOwnPropertyNames(target.prototype)){
            if (prop === 'handleRequest') continue;
            // Save the original function 
            let oldFunc: Function = target.prototype[prop];
            if(oldFunc instanceof Function) {
                target.prototype[prop] = function(){
                    this['handleRequest'](); // call the extra method
                    return oldFunc.apply(this, arguments); // call the original and return any result
                }
            }
        }
    }
}

@handleRequest()
export class ApiService {
    base_url: string = 'https://jsonplaceholder.typicode.com/posts';
    methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];

    /**
     * Create an instance of ApiService.
     * @param {string} base_url
     */
    constructor(base_url: string = null) {
        this.base_url = base_url ? base_url : this.base_url;
    }

    get(endpoint: string): string {
        return 'get method';
    }

    post(endpoint: string, data: any): string {
        return 'post method';
    }

    protected handleRequest(): void {
        console.log('handle the request');
    }
}

let s = new ApiService();
s.get("");
s.post("", null);