From e6ad230c6da40d16f1625a7a5a83e55281e21f0e Mon Sep 17 00:00:00 2001 From: Hunter Loftis Date: Sat, 3 Mar 2012 17:14:48 -0500 Subject: [PATCH] Implemented timeout() and req.clearTimeout() --- lib/middleware/timeout.js | 38 ++++++++++++++++++++++++++++++++++++++ test/timeout.js | 3 ++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/lib/middleware/timeout.js b/lib/middleware/timeout.js index 38978b9a8..be295ddee 100644 --- a/lib/middleware/timeout.js +++ b/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(); }; } \ No newline at end of file diff --git a/test/timeout.js b/test/timeout.js index 14b0dcb0c..687fe4aaa 100644 --- a/test/timeout.js +++ b/test/timeout.js @@ -4,6 +4,7 @@ var connect = require('../'); var app = connect(); app.use(connect.timeout({ + code: 503, time: 500 })); @@ -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(); }); });