Skip to content

Commit

Permalink
chore: removes code duplication at handling HEAD method (#1400)
Browse files Browse the repository at this point in the history
  • Loading branch information
tinovyatkin authored and dead-horse committed Oct 15, 2019
1 parent f155785 commit be7d334
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 5 deletions.
8 changes: 4 additions & 4 deletions lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ const debug = require('debug')('koa:application');
const onFinished = require('on-finished');
const response = require('./response');
const compose = require('koa-compose');
const isJSON = require('koa-is-json');
const context = require('./context');
const request = require('./request');
const statuses = require('statuses');
Expand Down Expand Up @@ -225,9 +224,10 @@ function respond(ctx) {
return res.end();
}

if ('HEAD' == ctx.method) {
if (!res.headersSent && isJSON(body)) {
ctx.length = Buffer.byteLength(JSON.stringify(body));
if ('HEAD' === ctx.method) {
if (!res.headersSent && !ctx.response.has('Content-Length')) {
const { length } = ctx.response;
if (Number.isInteger(length)) ctx.length = length;
}
return res.end();
}
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
"is-generator-function": "^1.0.7",
"koa-compose": "^4.1.0",
"koa-convert": "^1.2.0",
"koa-is-json": "^1.0.0",
"on-finished": "^2.3.0",
"only": "~0.0.2",
"parseurl": "^1.3.2",
Expand Down
20 changes: 20 additions & 0 deletions test/application/respond.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,26 @@ describe('app.respond', () => {
assert(!res.text);
});

it('should keep stream header if set manually', async() => {
const app = new Koa();

const { length } = fs.readFileSync('package.json');

app.use(ctx => {
ctx.length = length;
ctx.body = fs.createReadStream('package.json');
});

const server = app.listen();

const res = await request(server)
.head('/')
.expect(200);

assert.equal(res.header['content-length'], length);
assert(!res.text);
});

it('should respond with a 404 if no body was set', () => {
const app = new Koa();

Expand Down

0 comments on commit be7d334

Please sign in to comment.