Fix Headers iterable initializer handling

This commit is contained in:
Timothy Gu 2017-01-14 21:11:30 -08:00
parent f198f93767
commit 502b604208
2 changed files with 28 additions and 4 deletions

View File

@ -44,10 +44,14 @@ export default class Headers {
this.append(name, value);
}
}
} else if (Array.isArray(headers)) {
} else if (typeof headers === 'object' && headers[Symbol.iterator]) {
// array of tuples
for (let el of headers) {
if (!Array.isArray(el) || el.length !== 2) {
if (typeof el !== 'object' || !el[Symbol.iterator]) {
throw new TypeError('Header pairs must be an iterable object');
}
el = Array.from(el);
if (el.length !== 2) {
throw new TypeError('Header pairs must contain exactly two items');
}
this.append(el[0], el[1]);
@ -59,6 +63,8 @@ export default class Headers {
// will handle it.
this.append(prop, headers[prop]);
}
} else if (headers != null) {
throw new TypeError('Provided initializer must be an object');
}
Object.defineProperty(this, Symbol.toStringTag, {

View File

@ -1435,19 +1435,37 @@ describe(`node-fetch with FOLLOW_SPEC = ${defaultFollowSpec}`, () => {
expect(h3Raw['b']).to.include('1');
});
it('should accept headers as an array of tuples', function() {
const headers = new Headers([
it('should accept headers as an iterable of tuples', function() {
let headers;
headers = new Headers([
['a', '1'],
['b', '2'],
['a', '3']
]);
expect(headers.getAll('a')).to.deep.equal(['1', '3']);
expect(headers.getAll('b')).to.deep.equal(['2']);
headers = new Headers([
new Set(['a', '1']),
['b', '2'],
new Map([['a', null], ['3', null]]).keys()
]);
expect(headers.getAll('a')).to.deep.equal(['1', '3']);
expect(headers.getAll('b')).to.deep.equal(['2']);
headers = new Headers(new Map([
['a', '1'],
['b', '2']
]));
expect(headers.getAll('a')).to.deep.equal(['1']);
expect(headers.getAll('b')).to.deep.equal(['2']);
});
it('should throw a TypeError if non-tuple exists in a headers initializer', function() {
expect(() => new Headers([ ['b', '2', 'huh?'] ])).to.throw(TypeError);
expect(() => new Headers([ 'b2' ])).to.throw(TypeError);
expect(() => new Headers('b2')).to.throw(TypeError);
});
it('should support fetch with Request instance', function() {