forked from expressjs/timeout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (64 loc) · 1.39 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
/*!
* connect-timeout
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
*/
var createError = require('http-errors')
var ms = require('ms')
var onFinished = require('on-finished')
var onHeaders = require('on-headers')
/**
* Module exports.
*/
module.exports = timeout
function onTimeout(delay, cb) {
return function () {
cb(createError(503, 'Response timeout', {
code: 'ETIMEDOUT',
timeout: delay
}))
}
}
/**
* Timeout:
*
* See README.md for documentation.
*
* @param {Number} time
* @param {Object} options
* @return {Function} middleware
* @api 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
var onTimeout = opts.onTimeout || onTimeout;
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()
}
}