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...

2
  • @world more mongoose-named-scopes woes Commented Jun 24, 2016 at 2:38
  • 2
    For future searchers, I think I've come up with a solution to a similar problem here: stackoverflow.com/questions/41886355/… Commented Jan 27, 2017 at 5:43

1 Answer 1

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;
            }
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.