Skip to content

Commit 961911e

Browse files
gyszalaimcollina
authored andcommitted
Override Response.setTimeout to make response timeout handler work (#69)
* Override Response,setTimeout to make response timeout handler work * Fixes after review * Response.setTimeout emits timeout event on response instead of response.socket
1 parent 6997692 commit 961911e

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

lib/response.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,14 @@ function Response (req, onEnd, reject) {
4646

4747
util.inherits(Response, http.ServerResponse)
4848

49+
Response.prototype.setTimeout = function (msecs, callback) {
50+
this.timeoutHandle = setTimeout(() => {
51+
this.emit('timeout')
52+
}, msecs)
53+
this.on('timeout', callback)
54+
return this
55+
}
56+
4957
Response.prototype.writeHead = function () {
5058
const result = http.ServerResponse.prototype.writeHead.apply(this, arguments)
5159

@@ -65,6 +73,9 @@ Response.prototype.writeHead = function () {
6573
}
6674

6775
Response.prototype.write = function (data, encoding, callback) {
76+
if (this.timeoutHandle) {
77+
clearTimeout(this.timeoutHandle)
78+
}
6879
http.ServerResponse.prototype.write.call(this, data, encoding, callback)
6980
this._lightMyRequest.payloadChunks.push(Buffer.from(data, encoding))
7081
return true

test/test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -847,6 +847,28 @@ test('should handle response errors (promises)', (t) => {
847847
.catch(err => t.ok(err))
848848
})
849849

850+
test('should handle response timeout handler', (t) => {
851+
t.plan(3)
852+
const dispatch = function (req, res) {
853+
const handle = setTimeout(() => {
854+
res.writeHead(200, { 'Content-Type': 'text/plain' })
855+
res.end('incorrect')
856+
}, 200)
857+
res.setTimeout(100, () => {
858+
clearTimeout(handle)
859+
res.writeHead(200, { 'Content-Type': 'text/plain' })
860+
res.end('correct')
861+
})
862+
res.on('timeout', () => {
863+
t.ok(true, 'Response timeout event not emitted')
864+
})
865+
}
866+
inject(dispatch, { method: 'GET', url: '/test' }, (err, res) => {
867+
t.error(err)
868+
t.equal(res.payload, 'correct')
869+
})
870+
})
871+
850872
test('should throw on unknown HTTP method', (t) => {
851873
t.plan(1)
852874
const dispatch = function (req, res) { }

0 commit comments

Comments
 (0)