Skip to content

Commit

Permalink
feat: allow bodyless responses for non empty status codes
Browse files Browse the repository at this point in the history
  • Loading branch information
Eladio Mora committed Apr 20, 2020
1 parent 8ddab48 commit 4b74f17
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/application.js
Expand Up @@ -238,6 +238,11 @@ function respond(ctx) {

// status body
if (null == body) {
if (ctx.response._explicitNullBody) {
ctx.response.remove('Content-Type');
ctx.response.remove('Transfer-Encoding');
return res.end();
}
if (ctx.req.httpVersionMajor >= 2) {
body = String(code);
} else {
Expand Down
1 change: 1 addition & 0 deletions lib/response.js
Expand Up @@ -139,6 +139,7 @@ module.exports = {
// no content
if (null == val) {
if (!statuses.empty[this.status]) this.status = 204;
if (val === null) this._explicitNullBody = true;
this.remove('Content-Type');
this.remove('Content-Length');
this.remove('Transfer-Encoding');
Expand Down
37 changes: 37 additions & 0 deletions test/application/respond.js
Expand Up @@ -810,4 +810,41 @@ describe('app.respond', () => {
assert.equal(res.headers.hasOwnProperty('content-type'), false);
});
});

describe('with explicit null body', () => {
it.only('should preserve given status', async() => {
const app = new Koa();

app.use(ctx => {
ctx.body = null;
ctx.status = 404;
});

const server = app.listen();

return request(server)
.get('/')
.expect(404)
.expect('')
.expect({});
});
it.only('should respond with correct headers', async() => {
const app = new Koa();

app.use(ctx => {
ctx.body = null;
ctx.status = 401;
});

const server = app.listen();

const res = await request(server)
.get('/')
.expect(401)
.expect('')
.expect({});

assert.equal(res.headers.hasOwnProperty('content-type'), false);
});
});
});
28 changes: 28 additions & 0 deletions test/application/response.js
Expand Up @@ -10,6 +10,8 @@ describe('app.response', () => {
app1.response.msg = 'hello';
const app2 = new Koa();
const app3 = new Koa();
const app4 = new Koa();
const app5 = new Koa();

it('should merge properties', () => {
app1.use((ctx, next) => {
Expand Down Expand Up @@ -43,4 +45,30 @@ describe('app.response', () => {
.expect(404);
assert.equal(response.text, '404');
});

it('should set ._explicitNullBody correctly', async() => {
app4.use((ctx, next) => {
ctx.body = null;
assert.strictEqual(ctx.response._explicitNullBody, true);
});

return request(app4.listen())
.get('/')
.expect(204);
});

it('should not set ._explicitNullBody incorrectly', async() => {
app5.use((ctx, next) => {
ctx.body = undefined;
assert.strictEqual(ctx.response._explicitNullBody, undefined);
ctx.body = '';
assert.strictEqual(ctx.response._explicitNullBody, undefined);
ctx.body = false;
assert.strictEqual(ctx.response._explicitNullBody, undefined);
});

return request(app5.listen())
.get('/')
.expect(204);
});
});

0 comments on commit 4b74f17

Please sign in to comment.