feat(http): add support for ArrayBuffer

Add the buffer option to store response in ArrayBuffer
Improve the interface to get back response independently of the buffer type
This commit is contained in:
Damien Cassan
2016-02-24 16:37:18 +01:00
committed by Jeff Cross
parent 0ccb6e0dfc
commit 1266460386
12 changed files with 218 additions and 29 deletions

View File

@ -12,7 +12,7 @@ import {Json, isString} from '../src/facade/lang';
import {ResponseOptions} from './base_response_options';
import {ResponseType} from './enums';
import {Headers} from './headers';
import {isJsObject} from './http_utils';
import {isJsObject, stringToArrayBuffer} from './http_utils';
/**
@ -83,8 +83,10 @@ export class Response {
* Spec](https://fetch.spec.whatwg.org/#headers-class).
*/
headers: Headers;
// TODO: Support ArrayBuffer, JSON, FormData, Blob
private _body: string|Object;
// TODO: Support FormData, Blob
private _body: string | Object | ArrayBuffer;
constructor(responseOptions: ResponseOptions) {
this._body = responseOptions.body;
this.status = responseOptions.status;
@ -95,12 +97,6 @@ export class Response {
this.url = responseOptions.url;
}
/**
* Not yet implemented
*/
// TODO: Blob return type
blob(): any { throw new BaseException('"blob()" method not implemented on Response superclass'); }
/**
* Attempts to return body as parsed `JSON` object, or raises an exception.
*/
@ -110,6 +106,10 @@ export class Response {
jsonResponse = this._body;
} else if (isString(this._body)) {
jsonResponse = Json.parse(<string>this._body);
} else if (this._body instanceof ArrayBuffer) {
jsonResponse = Json.parse(this.text());
} else {
jsonResponse = this._body;
}
return jsonResponse;
}
@ -117,17 +117,40 @@ export class Response {
/**
* Returns the body as a string, presuming `toString()` can be called on the response body.
*/
text(): string { return this._body.toString(); }
text(): string {
var textResponse: string;
if (this._body instanceof ArrayBuffer) {
textResponse = String.fromCharCode.apply(null, new Uint16Array(<ArrayBuffer>this._body));
} else if (isJsObject(this._body)) {
textResponse = Json.stringify(this._body);
} else {
textResponse = this._body.toString();
}
return textResponse;
}
/**
* Not yet implemented
* Return the body as an ArrayBuffer
*/
// TODO: ArrayBuffer return type
arrayBuffer(): any {
throw new BaseException('"arrayBuffer()" method not implemented on Response superclass');
arrayBuffer(): ArrayBuffer {
var bufferResponse: ArrayBuffer;
if (this._body instanceof ArrayBuffer) {
bufferResponse = <ArrayBuffer>this._body;
} else {
bufferResponse = stringToArrayBuffer(this.text());
}
return bufferResponse;
}
toString(): string {
return `Response with status: ${this.status} ${this.statusText} for URL: ${this.url}`;
}
/**
* Not yet implemented
*/
// TODO: Blob return type
blob(): any { throw new BaseException('"blob()" method not implemented on Response superclass'); }
}