超出StackSize - 尝试制作API

时间:2017-10-22 13:50:53

标签: node.js typescript api-design es6-proxy

我正在尝试在NodeJs上使用TypeScript和ES6 Proxies创建动态API。我实现了API,但经过一些测试后发现我超过了堆栈大小。即使我尝试将--stack-size设置为16000但仍然超过它!我想我有一些我没有看到的递归方法。

这是我的代码:

export class StackPlate {
public static build(name: string, parent: StackPlate, callback: (type: string, data: any) => any) {
    return (new StackPlate(name, parent, callback)).proxy;
}

private callback: (type: string, data: any) => any;
private parent: StackPlate;
private childs: {[key: string]:  StackPlate} = {};
private name: string = "";
public proxy;

constructor(name: string, parent: StackPlate, callback: (type: string, data: any) => any) {
    this.parent = parent;
    this.name = name;
    this.callback = callback;

    this.proxy = new Proxy((...parameters) => {
        let stack = [this.name];
        let parent = this.parent;
        while(parent) {
            stack.push(parent.getName());
            parent = parent.getParent();
        }
        stack = stack.reverse();
        return this.callback("call", {stack, parameters});
    }, {
        get: (target, property: string): any => {
            if(this.childs[property])
                return this.childs[property].proxy;

            let child = StackPlate.build(property, this, this.callback);
            this.childs[property] = child;

            this.callback("get", {target, property, child});

            return child.proxy;
        },
        set: (target, property: string, value: any, receiver): boolean => {
            let stack = [property, this.name];
            let parent = this.parent;
            while(parent) {
                stack.push(parent.getName());
                parent = parent.getParent();
            }
            stack = stack.reverse();
            return this.callback("set", {stack, property, target, value});
        }
    });
}

public getName() {
    return this.name;
}

public getChilds() {
    return this.childs;
}

public getParent() {
    return this.parent;
}
}

我正在使用TypeScript 2.4.2和Node 8.7.0(也尝试使用较低的8.x版本)。在我的配置中,我已将目标设置为es6。我无法理解我的问题是什么!

PS:测试:

let plate = StackPlate.build("test", undefined, console.log);
plate.a.b.c();  

1 个答案:

答案 0 :(得分:0)

发现问题!在获取陷阱中,我使用实际返回代理的StackPlate.build方法,而不是对象本身!这创造了一个循环:)