Jan Schmutz
Jan Schmutz

Reputation: 890

Javascript proxy for nested object (apply for all function calls)

I'm looking for away to use a proxy on a nested object. In this example I would like to add 1 in my proxy for the result of every function call in that object. How would I go about this, since I can't use apply on the testobj directly. Thanks for any input.

const testObj = {
  add: (a: number, b: number) => a + b,
  subtract: (a: number, b: number) => a - b,
  multiply: (a: number, b: number) => a * b,
  ...
}

const proxy = new Proxy(testObj, {
  // for the result of every function call (add / subtract ....)
  // i would like to add 1 to the result

})

Upvotes: 1

Views: 1073

Answers (1)

Jan Schmutz
Jan Schmutz

Reputation: 890

In the end I found the way to do. It was to return another proxy from the get trap. Just posting this in case anyone stumbles across the same problem.

const testProxy = new Proxy(testObj, {
  get: (
    target: typeof testObj,
    key: keyof typeof testObj,
  ): any => {
    if (typeof target[key] !== 'function') {
      return target[key]
    } else {
      return new Proxy(target[key], {
        apply: (
          target: any,
          thisArg: any,
          argArray?: any[],
        ): any => {
          console.log('triggered')
          return target(...argArray) + 1
        },
      })
    }
  },
})

Upvotes: 2

Related Questions