/**
* Intercept writes for head requests, do not send to client,
* but send length, and make body available in context.
+ * N.B. If persisted, ctx.responseBody will be a raw buffer, be aware when logging.
* @param {http.ClientRequest} req
* @param {http.ServerResponse} res
* @param {object} ctx
+ * @param {Boolean} persistResponseBody
*/
- static setHeadHandler(req, res, ctx) {
+ static setHeadHandler(req, res, ctx, persistResponseBody = false) {
if (req.method === 'HEAD') {
const origEnd = res.end.bind(res);
const chunks = [];
};
res.end = function (data, encoding, ...rest) {
Dingus.pushBufChunk(chunks, data, encoding);
- ctx.responseBody = Buffer.concat(chunks);
- res.setHeader(Enum.Header.ContentLength, Buffer.byteLength(ctx.responseBody));
+ const responseBody = Buffer.concat(chunks);
+ res.setHeader(Enum.Header.ContentLength, Buffer.byteLength(responseBody));
+ if (persistResponseBody) {
+ ctx.responseBody = responseBody;
+ }
return origEnd(undefined, encoding, ...rest);
};
}
};
ctx = {};
});
- it('collects body without writing', function () {
+ it('collects response without writing', function () {
Dingus.setHeadHandler(req, res, ctx);
res.write(Buffer.from('foo'));
res.write('baz');
res.end('quux');
assert(!origWrite.called);
assert(origEnd.called);
+ assert.deepStrictEqual(ctx.responseBody, undefined);
+ });
+ it('collects response without writing, persists written data', function () {
+ Dingus.setHeadHandler(req, res, ctx, true);
+ res.write(Buffer.from('foo'));
+ res.write('baz');
+ res.write();
+ res.end('quux');
+ assert(!origWrite.called);
+ assert(origEnd.called);
assert.deepStrictEqual(ctx.responseBody, Buffer.from('foobazquux'));
});
it('ignores non-head method', function () {