fix(http): fix Headers initialization from Headers and Object (#12106)

This commit is contained in:
Victor Berchet 2016-10-05 17:05:50 -07:00 committed by Tobias Bosch
parent a67c06708d
commit f4566f8128
2 changed files with 30 additions and 11 deletions

View File

@ -49,19 +49,16 @@ export class Headers {
} }
if (headers instanceof Headers) { if (headers instanceof Headers) {
headers._headers.forEach((value: string[], name: string) => { headers._headers.forEach((values: string[], name: string) => {
const lcName = name.toLowerCase(); values.forEach(value => this.append(name, value));
this._headers.set(lcName, value);
this.mayBeSetNormalizedName(name);
}); });
return; return;
} }
Object.keys(headers).forEach((name: string) => { Object.keys(headers).forEach((name: string) => {
const value = headers[name]; const values: string[] = Array.isArray(headers[name]) ? headers[name] : [headers[name]];
const lcName = name.toLowerCase(); this.delete(name);
this._headers.set(lcName, Array.isArray(value) ? value : [value]); values.forEach(value => this.append(name, value));
this.mayBeSetNormalizedName(name);
}); });
} }
@ -137,8 +134,13 @@ export class Headers {
* Sets or overrides header value for given name. * Sets or overrides header value for given name.
*/ */
set(name: string, value: string|string[]): void { set(name: string, value: string|string[]): void {
const strValue = Array.isArray(value) ? value.join(',') : value; if (Array.isArray(value)) {
this._headers.set(name.toLowerCase(), [strValue]); if (value.length) {
this._headers.set(name.toLowerCase(), [value.join(',')]);
}
} else {
this._headers.set(name.toLowerCase(), [value]);
}
this.mayBeSetNormalizedName(name); this.mayBeSetNormalizedName(name);
} }

View File

@ -37,6 +37,24 @@ export function main() {
secondHeaders.append('Content-Type', 'image/jpeg'); secondHeaders.append('Content-Type', 'image/jpeg');
expect(firstHeaders.has('Content-Type')).toEqual(false); expect(firstHeaders.has('Content-Type')).toEqual(false);
}); });
it('should preserve the list of values', () => {
const src = new Headers();
src.append('foo', 'a');
src.append('foo', 'b');
src.append('foo', 'c');
const dst = new Headers(src);
expect(dst.getAll('foo')).toEqual(src.getAll('foo'));
});
it('should keep the last value when initialized from an object', () => {
const headers = new Headers({
'foo': 'first',
'fOo': 'second',
});
expect(headers.getAll('foo')).toEqual(['second']);
});
}); });
describe('.set()', () => { describe('.set()', () => {
@ -140,7 +158,6 @@ export function main() {
ref = {'Accept': values}; ref = {'Accept': values};
}); });
it('should be serializable with toJSON', it('should be serializable with toJSON',
() => { expect(JSON.stringify(headers)).toEqual(JSON.stringify(ref)); }); () => { expect(JSON.stringify(headers)).toEqual(JSON.stringify(ref)); });