aboutsummaryrefslogtreecommitdiffstats
path: root/vnfmarket/src/main/webapp/vnfmarket/node_modules/connect-timeout/index.js
blob: c39a228874d4bbfc65678b552baf8993cb009556 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*!
 * connect-timeout
 * Copyright(c) 2014 Jonathan Ong
 * Copyright(c) 2014 Douglas Christopher Wilson
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var createError = require('http-errors');
var debug = require('debug')('connect:timeout');
var ms = require('ms');
var onHeaders = require('on-headers');

/**
 * Timeout:
 *
 * See README.md for documentation.
 *
 * @param {Number} time
 * @param {Object} options
 * @return {Function} middleware
 * @api public
 */

module.exports = function timeout(time, options) {
  options = options || {};

  time = typeof time === 'string'
    ? ms(time)
    : Number(time || 5000);

  var respond = !('respond' in options) || options.respond === true;

  return function(req, res, next) {
    var destroy = req.socket.destroy;
    var id = setTimeout(function(){
      req.timedout = true;
      req.emit('timeout', time);
    }, time);

    if (respond) {
      req.on('timeout', onTimeout(time, next));
    }

    req.clearTimeout = function(){
      clearTimeout(id);
    };

    req.socket.destroy = function(){
      clearTimeout(id);
      destroy.call(this);
    };

    req.timedout = false;

    onHeaders(res, function(){
      clearTimeout(id);
    });

    next();
  };
};

function onTimeout(time, cb){
  return function(){
    cb(createError(503, 'Response timeout', {
      code: 'ETIMEDOUT',
      timeout: time
    }));
  };
}