0

I'm trying to build a debug proxy so I can see requests and responses when calling various API's, but I'm stuck where I'm trying to send data to the original method.

How can I also send the chunk to the original method?

var httpProxy = require('http-proxy');

var write2;

function write (chunk, encoding) {

    /*  
        error: Object #<Object> has no method '_implicitHeader'
        because write2 is not a clone.
    */
    //write2(chunk, encoding);

    if (Buffer.isBuffer(chunk)) {
        console.log(chunk.toString(encoding));
    }
}


var server = httpProxy.createServer(function (req, res, proxy) {

    // copy .write
    write2 = res.write;
    // monkey-patch .write
    res.write = write;

    proxy.proxyRequest(req, res, {
        host: req.headers.host,
        port: 80
    });

});

server.listen(8000);

My project is here.

webjay
  • 5,358
  • 9
  • 45
  • 62

1 Answers1

0

Slightly modifying JavaScript: clone a function

Function.prototype.clone = function() {
    var that = this;
    var temp = function temporary() { return that.apply(this, arguments); };
    for( key in this ) {
        Object.defineProperty(temp,key,{
          get: function(){
            return that[key];
          },
          set: function(value){
            that[key] = value;
          }
        });
    }
    return temp;
};

I have changed the clone assignment to rather use getters and setters to ensure any changes to cloned function properties will reflect on the cloned object.

Now you can use something like write2 = res.write.clone().

One more thing, you may rather want to change this function from a prototype assignment to a normal method (pass in the function to clone) That will probably make your design slightly cleaner.

Community
  • 1
  • 1
major-mann
  • 2,602
  • 22
  • 37