Permalink
Browse files

Implemented timeout() and req.clearTimeout()

  • Loading branch information...
1 parent ab7b7be commit e6ad230c6da40d16f1625a7a5a83e55281e21f0e Hunter Loftis committed Mar 3, 2012
Showing with 40 additions and 1 deletion.
  1. +38 −0 lib/middleware/timeout.js
  2. +2 −1 test/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();
};
}
View
@@ -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();
});
});

0 comments on commit e6ad230

Please sign in to comment.