refactor(http): rewrite for readable & efficient.

This commit is contained in:
Zhicheng Wang 2016-07-29 13:19:49 +08:00 committed by Victor Berchet
parent 7f647822bd
commit 6134320f16
3 changed files with 18 additions and 13 deletions

View File

@ -64,13 +64,18 @@ export class Headers {
* Returns a new Headers instance from the given DOMString of Response Headers * Returns a new Headers instance from the given DOMString of Response Headers
*/ */
static fromResponseHeaderString(headersString: string): Headers { static fromResponseHeaderString(headersString: string): Headers {
return headersString.trim() let headers = new Headers();
.split('\n')
.map(val => val.split(':')) headersString.split('\n').forEach(line => {
.map(([key, ...parts]) => ([key.trim(), parts.join(':').trim()])) const index = line.indexOf(':');
.reduce( if (index > 0) {
(headers, [key, value]) => !headers.set(normalize(key), value) && headers, const key = line.substring(0, index);
new Headers()); const value = line.substring(index + 1).trim();
headers.set(key, value);
}
});
return headers;
} }
/** /**

View File

@ -571,9 +571,9 @@ export function main() {
sampleRequest, new MockBrowserXHR(), new ResponseOptions({status: statusCode})); sampleRequest, new MockBrowserXHR(), new ResponseOptions({status: statusCode}));
let responseHeaderString = `Date: Fri, 20 Nov 2015 01:45:26 GMT let responseHeaderString = `Date: Fri, 20 Nov 2015 01:45:26 GMT
Content-Type: application/json; charset=utf-8 Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked Transfer-Encoding: chunked
Connection: keep-alive`; Connection: keep-alive`;
connection.response.subscribe((res: Response) => { connection.response.subscribe((res: Response) => {
expect(res.headers.get('Date')).toEqual('Fri, 20 Nov 2015 01:45:26 GMT'); expect(res.headers.get('Date')).toEqual('Fri, 20 Nov 2015 01:45:26 GMT');

View File

@ -109,9 +109,9 @@ export function main() {
it('should parse a response header string', () => { it('should parse a response header string', () => {
let responseHeaderString = `Date: Fri, 20 Nov 2015 01:45:26 GMT let responseHeaderString = `Date: Fri, 20 Nov 2015 01:45:26 GMT
Content-Type: application/json; charset=utf-8 Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked Transfer-Encoding: chunked
Connection: keep-alive`; Connection: keep-alive`;
let responseHeaders = Headers.fromResponseHeaderString(responseHeaderString); let responseHeaders = Headers.fromResponseHeaderString(responseHeaderString);