0

What I am trying to do is intercept a function call, and prepend a header. The header is getting applied, the function itself is getting called, but the results don't have actually body.

code:


'use strict'
const load = require('require.all')
module.exports = ({xr}) => {
  const cmds = load({
    dir: __dirname,
    not: /index\.js$/i
  })(xr);
  const result = Object.entries(cmds).map(([k,v]) => {
    return {
      [k] : new Proxy(v, {
        get: function (target, prop) {
          return (...args) => {
            return {
              type: 'cmd',
              ...(target[prop])(args)
            }
          }
        },
      })
    }
  }).reduce((a,b) => Object.assign({},a,b))
  return result
}

The original function will return something like:

{
  blocks:[...]
}

and I need to prepend this header.

expected output:

{
  type: "cmd",
  blocks: [...]
}

I would give you what I am getting as JSON except, it chokes on JSON.stringify because of this proxy. However, in my debugger (and my code agrees because it blows up) the only thing there is type: "cmd"

Am I doing this right?

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
Christian Bongiorno
  • 5,150
  • 3
  • 38
  • 76
  • 1
    Don't use a proxy to wrap a function. A simple closure will be enough. – Bergi Apr 28 '21 at 02:33
  • 1
    Can you give a [mcve], including the functions to be wrapped and how the proxied functions are invoked? – Bergi Apr 28 '21 at 02:35
  • @Bergi - I decided that, although it doesn't answer the question, I am taking your advice about a simple closure. I will consider closing the question because I can't actually give you what you ask for – Christian Bongiorno Apr 28 '21 at 04:00

0 Answers0