Skip to content

Commit

Permalink
Implemented timeout() and req.clearTimeout()
Browse files Browse the repository at this point in the history
  • Loading branch information
Hunter Loftis committed Mar 3, 2012
1 parent ab7b7be commit e6ad230
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
38 changes: 38 additions & 0 deletions lib/middleware/timeout.js
@@ -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();
};
}
3 changes: 2 additions & 1 deletion test/timeout.js
Expand Up @@ -4,6 +4,7 @@ var connect = require('../');
var app = connect();

app.use(connect.timeout({
code: 503,
time: 500
}));

Expand Down Expand Up @@ -31,7 +32,7 @@ describe('connect.timeout()', function() {
app.request()
.get('/should/timeout')
.end(function(res) {
res.statusCode.should.equal(500);
res.statusCode.should.equal(503);
done();
});
});
Expand Down

0 comments on commit e6ad230

Please sign in to comment.