From 0e829c17ad20c7153d77f890d0e51d96e514285a Mon Sep 17 00:00:00 2001 From: Jonathan Ong Date: Fri, 4 Oct 2013 00:08:47 -0700 Subject: [PATCH] set length on body override --- lib/context.js | 12 ++++++------ test/context.js | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/lib/context.js b/lib/context.js index 12762e3..77cf5fd 100644 --- a/lib/context.js +++ b/lib/context.js @@ -163,31 +163,31 @@ module.exports = { return; } - // content-type already set - if (this.responseHeader['content-type']) return; + // set the content-type only if not yet set + var setType = !this.responseHeader['content-type']; // string if ('string' == typeof val) { - this.type = ~val.indexOf('<') ? 'html' : 'text'; + if (setType) this.type = ~val.indexOf('<') ? 'html' : 'text'; this.length = Buffer.byteLength(val); return; } // buffer if (Buffer.isBuffer(val)) { - this.type = 'bin'; + if (setType) this.type = 'bin'; this.length = val.length; return; } // stream if (val instanceof Stream) { - this.type = 'bin'; + if (setType) this.type = 'bin'; return; } // json - this.type = 'json'; + if (setType) this.type = 'json'; }, /** diff --git a/test/context.js b/test/context.js index 60b121c..5365958 100644 --- a/test/context.js +++ b/test/context.js @@ -29,6 +29,13 @@ describe('ctx.body=', function(){ ctx.body = new Buffer('something'); assert('image/png' == ctx.responseHeader['content-type']); }) + + it('should override length', function(){ + var ctx = context(); + ctx.type = 'html'; + ctx.body = 'something'; + assert.equal(ctx.responseLength, 9); + }) }) describe('when a string is given', function(){ @@ -51,6 +58,21 @@ describe('ctx.body=', function(){ ctx.body = '

Tobi

'; assert('text/html; charset=utf-8' == ctx.responseHeader['content-type']); }) + + it('should set length', function(){ + var string = '

Tobi

'; + var ctx = context(); + ctx.body = string; + assert.equal(ctx.responseLength, Buffer.byteLength(string)); + }) + + it('should set length when body is override', function(){ + var string = '

Tobi

'; + var ctx = context(); + ctx.body = string; + ctx.body = string + string; + assert.equal(ctx.responseLength, 2 * Buffer.byteLength(string)); + }) }) describe('when a stream is given', function(){