node-replay icon indicating copy to clipboard operation
node-replay copied to clipboard

Not working when code listens for 'socket' event.

Open tonyd256 opened this issue 7 years ago • 0 comments

I'm trying to use node-relay to stub out stripe-node library. At first, simply adding this library was causing all my stripe requests to immediately timeout. I did some digging and found that when calling setTimeout on the ProxyRequest it's calling the timeout callback immediately: https://github.com/assaf/node-replay/blob/master/src/proxy.js#L81 I simply commented this out. You can see the Stripe API call setTimeout causing this to fire: https://github.com/stripe/stripe-node/blob/master/lib/StripeResource.js#L297

This was not the only change I needed though. After commenting out that line, my tests were still timing out. I saw that Stripe is waiting for the 'socket' event to emit. Then waiting for that socket to emit a 'connect' event. I emitted those events from the request proxy and everything now works as expected.

// Route HTTP requests to our little helper.
HTTP.request = function (options, callback) {
  if (typeof options === 'string' || options instanceof String) options = URL.parse(options);

  // WebSocket request: pass through to Node.js library
  if (options.headers && options.headers.Upgrade === 'websocket') return new HTTP.ClientRequest(options, callback);

  const hostname = options.hostname || options.host && options.host.split(':')[0] || 'localhost';
  if (Replay.isLocalhost(hostname) || Replay.isPassThrough(hostname)) return new HTTP.ClientRequest(options, callback);

  // Proxy request
  const request = new ProxyRequest(options, Replay.chain.start);
  if (callback) request.once('response', callback);
  // -----------------------------------------------------------------------------
  // I added this setTimeout
  setTimeout(function () {
    request.emit('socket', request);
    request.emit('secureConnect');
  }, 100);
  // -----------------------------------------------------------------------------
  return request;
};

I'm not sure how to proceed here. I'm not very familiar with this library so I don't know if this is expected or a bug or just not implemented yet. I'm happy to make a PR if you can provide some guidance on how to properly get this working.

tonyd256 avatar Oct 12 '17 23:10 tonyd256