Skip to content

Commit

Permalink
Support backpressure when streaming the payload (#328)
Browse files Browse the repository at this point in the history
Signed-off-by: Matteo Collina <[email protected]>
  • Loading branch information
mcollina authored Jan 8, 2025
1 parent 6d888c8 commit fa62c68
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,11 @@ Response.prototype.write = function (data, encoding, callback) {
}
http.ServerResponse.prototype.write.call(this, data, encoding, callback)
if (this._lightMyRequest.stream) {
this._lightMyRequest.stream.push(Buffer.from(data, encoding))
return this._lightMyRequest.stream.push(Buffer.from(data, encoding))
} else {
this._lightMyRequest.payloadChunks.push(Buffer.from(data, encoding))
return true
}
return true
}

Response.prototype.end = function (data, encoding, callback) {
Expand Down
25 changes: 25 additions & 0 deletions test/stream.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,31 @@ test('stream mode - returns chunked payload', (t, done) => {
})
})

test('stream mode - backpressure', (t, done) => {
t.plan(7)
let expected
const dispatch = function (_req, res) {
res.writeHead(200, 'OK')
res.write('a')
const buf = Buffer.alloc(1024 * 1024).fill('b')
t.assert.strictEqual(res.write(buf), false)
expected = 'a' + buf.toString()
res.end()
}

inject(dispatch, { method: 'GET', url: '/', payloadAsStream: true }, (err, res) => {
t.assert.ifError(err)
t.assert.ok(res.headers.date)
t.assert.ok(res.headers.connection)
t.assert.strictEqual(res.headers['transfer-encoding'], 'chunked')
accumulate(res.stream(), (err, payload) => {
t.assert.ifError(err)
t.assert.strictEqual(payload.toString(), expected)
done()
})
})
})

test('stream mode - sets trailers in response object', (t, done) => {
t.plan(4)
const dispatch = function (_req, res) {
Expand Down

0 comments on commit fa62c68

Please sign in to comment.