Search code examples
node.jsecmascript-6es6-proxy

Why is my function proxy not being called in Node?


I was using proxy get method fine. Then I tried using it on a function and quickly realized I needed to use the apply method. This simple example is not working. It never enters apply.

Node looks to support apply https://node.green/#ES2015-built-ins-Proxy--apply--handler. Not sure what I'm doing wrong.

var Foo = {
  runme: function() {
    return 1;
  }
};

var Magic = {
  Foo: Foo
};

Magic.Foo = new Proxy(Object.assign({}, Magic.Foo), {
  apply: function(target, thisArg, argumentsList) {
    // never gets in here
    console.log('Proxying function call');
    console.log(target);
    return 2;
  }
});

console.log(Foo.runme()); // outputs 1
console.log(Magic.Foo.runme()); // outputs 1

I tried both Proxy on Magic.foo directly and via the Object.assign to see if it needed to be its own object or not. Neither worked.


Solution

  • You assume here that apply traps work like get traps -- i.e., for any property of the proxied object -- but they do not. The apply trap runs when the Proxy itself is called a function. Here, your proxy is Magic.Foo, but you never call Magic.Foo(). You only call Magic.Foo.runme(), which is not a proxied function.

    You must wrap each function whose invocation you wish to intercept in its own individual Proxy wrapper.

    Alternatively, you could use a get trap on Magic.Foo that returns a function with the appropriate behavior for each accessed property.