arnaucube
arnaucube/comunicationLeapPublic Self-hosted repository
comunicationLeap/node_modules/connect/lib/middleware/timeout.js
node_modules/connect/lib/middleware/timeout.jsRaw
 1/*!
 2 * Connect - timeout
 3 * Ported from https://github.com/LearnBoost/connect-timeout
 4 * MIT Licensed
 5 */
 6
 7/**
 8 * Module dependencies.
 9 */
10
11var debug = require('debug')('connect:timeout');
12
13/**
14 * Timeout:
15 *
16 * Times out the request in `ms`, defaulting to `5000`. The
17 * method `req.clearTimeout()` is added to revert this behaviour
18 * programmatically within your application's middleware, routes, etc.
19 *
20 * The timeout error is passed to `next()` so that you may customize
21 * the response behaviour. This error has the `.timeout` property as
22 * well as `.status == 408`.
23 *
24 * @param {Number} ms
25 * @return {Function}
26 * @api public
27 */
28
29module.exports = function timeout(ms) {
30  ms = ms || 5000;
31
32  return function(req, res, next) {
33    var id = setTimeout(function(){
34      req.emit('timeout', ms);
35    }, ms);
36
37    req.on('timeout', function(){
38      if (res.headerSent) return debug('response started, cannot timeout');
39      var err = new Error('Response timeout');
40      err.timeout = ms;
41      err.status = 503;
42      next(err);
43    });
44
45    req.clearTimeout = function(){
46      clearTimeout(id);
47    };
48
49    res.on('header', function(){
50      clearTimeout(id);
51    });
52
53    next();
54  };
55};