Search code examples
javascripttypescriptes6-proxy

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

})

Solution

  • 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
            },
          })
        }
      },
    })