forked from senchalabs/connect
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implemented timeout() and req.clearTimeout()
- Loading branch information
Hunter Loftis
committed
Mar 3, 2012
1 parent
ab7b7be
commit e6ad230
Showing
2 changed files
with
40 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,43 @@ | ||
/*! | ||
* Connect - timeout | ||
* Copyright(c) 2012 Hunter Loftis | ||
* MIT Licensed | ||
*/ | ||
|
||
/** | ||
* Timeout: | ||
* | ||
* Invokes `socket.setTimeout` to timeout idle requests | ||
* Adds req.clearTimeout() for long-running requests | ||
* | ||
* - `throwError`: throw an error instead of writing a status code | ||
* - `time`: timeout length in ms (default: 10000) | ||
* | ||
* @param {Object} options | ||
* @return {Function} | ||
* @api public | ||
*/ | ||
|
||
module.exports = function timeout(options) { | ||
return function(req, res, next) { | ||
|
||
req.socket.removeAllListeners('timeout'); // http socket auto-destroys on timeout | ||
req.socket.setTimeout(options.time || 10000, timed_out); | ||
|
||
function timed_out() { | ||
if (options.throwError) { | ||
return next(new Error('Timeout ' + at)); | ||
} | ||
else { | ||
res.writeHead(options.code || 500); | ||
res.end(); | ||
} | ||
} | ||
|
||
req.clearTimeout = function() { | ||
req.socket.setTimeout(0); | ||
}; | ||
|
||
return next(); | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters