3

I want to be able to do this:

x.where('age').gt(20);

x.__calls  // [['where', ['age']], ['gt', [20]]]

where and gt are just examples. I do not know what functions will be called, they might be anything, and they don't do anything apart from filling the __calls array.

So far I have the following code which uses ES6's Proxy object

var x = new Proxy({ 
    __calls: [] 
}, {
    get: function (target, name) {
        if (name in target) {
            return target[name];
        } else {
            return () => {
                target.__calls.push([name, Array.prototype.slice.call(arguments)]);
                return x;
            }
        }
    }
});

If I remove the return x line, I can do x.where('age'); x.gt(20) to get the correct __calls. However, with the return x, it goes into infinite recursion for some reason...

gberger
  • 2,813
  • 3
  • 28
  • 50
  • @world more mongoose-named-scopes woes – gberger Jun 24 '16 at 02:38
  • 2
    For future searchers, I think I've come up with a solution to a similar problem here: http://stackoverflow.com/questions/41886355/capturing-all-chained-methods-and-getters-using-a-proxy-for-lazy-execution –  Jan 27 '17 at 05:43

1 Answers1

2

I added console.log(name) to find out what calls were responsible for the infinite recursion, and it turns out it was inspect and constructor. So I just blacklisted them :)

var x = new Proxy({ 
    __calls: [] 
}, {
    get: function (target, name) {
        if (name in target || name === 'inspect' || name === 'constructor') {
            return target[name];
        } else {
            return function() {
                target.__calls.push([name, Array.prototype.slice.call(arguments)]);
                return x;
            }
        }
    }
});
gberger
  • 2,813
  • 3
  • 28
  • 50