From 0b930665a8dd6fc607dbd1fe19cf36c10fe00a02 Mon Sep 17 00:00:00 2001 From: Yiyu He Date: Thu, 12 Jul 2018 14:10:12 +0800 Subject: [PATCH] perf: avoid stringify when set header (#1220) --- lib/response.js | 4 ++-- test/response/header.js | 3 ++- test/response/set.js | 8 +++++++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/lib/response.js b/lib/response.js index e42506f..8092c7a 100644 --- a/lib/response.js +++ b/lib/response.js @@ -439,8 +439,8 @@ module.exports = { if (this.headerSent) return; if (2 == arguments.length) { - if (Array.isArray(val)) val = val.map(String); - else val = String(val); + if (Array.isArray(val)) val = val.map(v => typeof v === 'string' ? v : String(v)); + else if (typeof val !== 'string') val = String(val); this.res.setHeader(field, val); } else { for (const key in field) { diff --git a/test/response/header.js b/test/response/header.js index b78c405..b7ccfc1 100644 --- a/test/response/header.js +++ b/test/response/header.js @@ -10,7 +10,8 @@ describe('res.header', () => { it('should return the response header object', () => { const res = response(); res.set('X-Foo', 'bar'); - assert.deepEqual(res.header, { 'x-foo': 'bar' }); + res.set('X-Number', 200); + assert.deepEqual(res.header, { 'x-foo': 'bar', 'x-number': '200' }); }); it('should use res.getHeaders() accessor when available', () => { diff --git a/test/response/set.js b/test/response/set.js index 8a21a05..710b458 100644 --- a/test/response/set.js +++ b/test/response/set.js @@ -11,12 +11,18 @@ describe('ctx.set(name, val)', () => { assert.equal(ctx.response.header['x-foo'], 'bar'); }); - it('should coerce to a string', () => { + it('should coerce number to string', () => { const ctx = context(); ctx.set('x-foo', 5); assert.equal(ctx.response.header['x-foo'], '5'); }); + it('should coerce undefined to string', () => { + const ctx = context(); + ctx.set('x-foo', undefined); + assert.equal(ctx.response.header['x-foo'], 'undefined'); + }); + it('should set a field value of array', () => { const ctx = context(); ctx.set('x-foo', ['foo', 'bar']);