打字稿|每次调用函数时调用函数

时间:2018-03-05 21:19:04

标签: class typescript ecmascript-6

我正在尝试编写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 个答案:

答案 0 :(得分:2)

您可以使用装饰器执行此操作,该装饰器将使用调用原始实现和额外方法的方法覆盖该类的所有方法:

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);
相关问题