perf: avoid stringify when set header (#1220)

master
Yiyu He 2018-07-12 14:10:12 +08:00 committed by GitHub
parent c6b8782553
commit 0b930665a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 11 additions and 4 deletions

View File

@ -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) {

View File

@ -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', () => {

View File

@ -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']);