Skip to content

Commit be7d334

Browse files
tinovyatkindead-horse
authored andcommitted
chore: removes code duplication at handling HEAD method (#1400)
1 parent f155785 commit be7d334

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

lib/application.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ const debug = require('debug')('koa:application');
1010
const onFinished = require('on-finished');
1111
const response = require('./response');
1212
const compose = require('koa-compose');
13-
const isJSON = require('koa-is-json');
1413
const context = require('./context');
1514
const request = require('./request');
1615
const statuses = require('statuses');
@@ -225,9 +224,10 @@ function respond(ctx) {
225224
return res.end();
226225
}
227226

228-
if ('HEAD' == ctx.method) {
229-
if (!res.headersSent && isJSON(body)) {
230-
ctx.length = Buffer.byteLength(JSON.stringify(body));
227+
if ('HEAD' === ctx.method) {
228+
if (!res.headersSent && !ctx.response.has('Content-Length')) {
229+
const { length } = ctx.response;
230+
if (Number.isInteger(length)) ctx.length = length;
231231
}
232232
return res.end();
233233
}

package.json

-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@
4040
"is-generator-function": "^1.0.7",
4141
"koa-compose": "^4.1.0",
4242
"koa-convert": "^1.2.0",
43-
"koa-is-json": "^1.0.0",
4443
"on-finished": "^2.3.0",
4544
"only": "~0.0.2",
4645
"parseurl": "^1.3.2",

test/application/respond.js

+20
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,26 @@ describe('app.respond', () => {
173173
assert(!res.text);
174174
});
175175

176+
it('should keep stream header if set manually', async() => {
177+
const app = new Koa();
178+
179+
const { length } = fs.readFileSync('package.json');
180+
181+
app.use(ctx => {
182+
ctx.length = length;
183+
ctx.body = fs.createReadStream('package.json');
184+
});
185+
186+
const server = app.listen();
187+
188+
const res = await request(server)
189+
.head('/')
190+
.expect(200);
191+
192+
assert.equal(res.header['content-length'], length);
193+
assert(!res.text);
194+
});
195+
176196
it('should respond with a 404 if no body was set', () => {
177197
const app = new Koa();
178198

0 commit comments

Comments
 (0)