打字稿|每次调用函数时都调用一个函数 [英] Typescript | Call a function every time a function is called

查看:41
本文介绍了打字稿|每次调用函数时都调用一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a Typescript API service. For the service I need a way to check that the method exists when a function such as get is called.

我知道我会喜欢

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

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

但是我并不是特别想在每个方法中都做到这一点,所以我不知道是否有一种方法可以在Typescript类的构造函数中侦听子函数的调用.

But I don't particularly want to do that are the top of every method so I didn't know if there was a way to listen within the constructor of the Typescript class for a call of a child function.

能够做到这一点似乎有些牵强,但是在像我这样的情况下这将非常有用,因此我不必继续这样做.

It seems a little far fetched to be able to do this but it would be extremely useful in cases like mine so I don't have to keep on doing it.

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';
    }
}

推荐答案

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

You can do this using a decorator that will override all methods of the class with a method that calls the original implementation and your extra method:

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);

这篇关于打字稿|每次调用函数时都调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆