2

I just want to confirm that I'm not missing something with regards to managing context and overriding methods. I'm using the http-proxy module in a node.js app and I need to override the function HttpProxy.prototype.proxyRequest. I'd like to do it without modifying the original module code directly but haven't been able to find a way to do it.

If I do this:

var httpProxy = require('http-proxy'),
httpProxyOverride = require('./http-proxy-override.js');

httpProxy.HttpProxy.prototype.proxyRequest = httpProxyOverride.proxyRequestOverride;

Then I lose the original context and errors are thrown. If I use apply(), I can provide a new context, but it doesn't appear I can persist the original context.

Based off of this SO thread: Is it possible to call function.apply without changing the context? It doesn't appear that there is a way to achieve what I'm trying to do and I'm hoping that someone can confirm this or correct me if I'm wrong.

Community
  • 1
  • 1
opike
  • 7,053
  • 14
  • 68
  • 95

1 Answers1

5

What about saving the old function and then overwriting it like:

var old = httpProxy.HttpProxy.prototype.proxyRequest;
httpProxy.HttpProxy.prototype.proxyRequest = function () {
  old.apply(this, arguments);
  //do more stuff
}

taken from Javascript: Extend a Function

Community
  • 1
  • 1
luk2302
  • 55,258
  • 23
  • 97
  • 137
  • It turns out that my original approach was incorrect. http-proxy provides an event ('proxyResponse') that provides access to altering the necessary behavior vs. overriding the code directly. However it was your response that resulted in my stumbling across this discovery so I'll give you credit. Thanks. – opike Jun 03 '13 at 05:58