Skip to content

Commit

Permalink
Fix another self mention.
Browse files Browse the repository at this point in the history
Fixes #171
  • Loading branch information
RubenVerborgh committed Sep 14, 2021
1 parent f26c6c6 commit eb6e76f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
21 changes: 14 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,8 @@ RedirectableRequest.prototype.removeHeader = function (name) {
// Global timeout for all underlying requests
RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
var self = this;
if (callback) {
this.on("timeout", callback);
}

// Destroys the socket on timeout
function destroyOnTimeout(socket) {
socket.setTimeout(msecs);
socket.removeListener("timeout", socket.destroy);
Expand All @@ -169,25 +167,34 @@ RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
destroyOnTimeout(socket);
}

// Prevent a timeout from triggering
// Stops a timeout from triggering
function clearTimer() {
clearTimeout(self._timeout);
if (self._timeout) {
clearTimeout(self._timeout);
self._timeout = null;
}
if (callback) {
self.removeListener("timeout", callback);
}
if (!this.socket) {
if (!self.socket) {
self._currentRequest.removeListener("socket", startTimer);
}
}

// Start the timer when the socket is opened
// Attach callback if passed
if (callback) {
this.on("timeout", callback);
}

// Start the timer if or when the socket is opened
if (this.socket) {
startTimer(this.socket);
}
else {
this._currentRequest.once("socket", startTimer);
}

// Clean up on events
this.on("socket", destroyOnTimeout);
this.once("response", clearTimer);
this.once("error", clearTimer);
Expand Down
19 changes: 19 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,25 @@ describe("follow-redirects", function () {
});
});

it("handles errors occuring before a socket is established", function () {
app.get("/redirect", redirectsTo("http:https://localhost:3602/b"));

var req;
return server.start(app)
.then(asPromise(function (resolve, reject) {
req = http.get("http:https://localhost:3600/redirect", reject);
req.setTimeout(3000, function () {
throw new Error("should not have timed out");
});
req.emit("error", new Error());
req.on("error", resolve);
}))
.then(function (error) {
assert.equal(error.code, "ECONNREFUSED");
clock.tick(5000);
});
});

it("sets a timeout when the socket already exists", function () {
app.get("/timeout", delay(clock, 5000, sendsJson({ timed: "out" })));

Expand Down

1 comment on commit eb6e76f

@fatoldsun00
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot for reactivity

Please sign in to comment.