-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
index.js
89 lines (71 loc) · 1.65 KB
/
index.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*!
* connect-timeout
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var createError = require('http-errors')
var ms = require('ms')
var onFinished = require('on-finished')
var onHeaders = require('on-headers')
/**
* Module exports.
* @public
*/
module.exports = timeout
/**
* Create a new timeout middleware.
*
* @param {number|string} [time=5000] The timeout as a number of milliseconds or a string for `ms`
* @param {object} [options] Additional options for middleware
* @param {boolean} [options.respond=true] Automatically emit error when timeout reached
* @return {function} middleware
* @public
*/
function timeout (time, options) {
var opts = options || {}
var delay = typeof time === 'string'
? ms(time)
: Number(time || 5000)
var respond = opts.respond === undefined || opts.respond === true
return function (req, res, next) {
var id = setTimeout(function () {
req.timedout = true
req.emit('timeout', delay)
}, delay)
if (respond) {
req.on('timeout', onTimeout(delay, next))
}
req.clearTimeout = function () {
clearTimeout(id)
}
req.timedout = false
onFinished(res, function () {
clearTimeout(id)
})
onHeaders(res, function () {
clearTimeout(id)
})
next()
}
}
/**
* Create timeout listener function.
*
* @param {number} delay
* @param {function} cb
* @private
*/
function onTimeout (delay, cb) {
return function () {
cb(createError(503, 'Response timeout', {
code: 'ETIMEDOUT',
timeout: delay
}))
}
}