2016-05-26 18:47:20 -04:00
|
|
|
/**
|
|
|
|
* @license
|
|
|
|
* Copyright Google Inc. All Rights Reserved.
|
|
|
|
*
|
|
|
|
* Use of this source code is governed by an MIT-style license that can be
|
|
|
|
* found in the LICENSE file at https://angular.io/license
|
|
|
|
*/
|
|
|
|
|
2016-11-15 12:19:14 -05:00
|
|
|
import {stringToArrayBuffer} from './http_utils';
|
2016-05-26 18:47:20 -04:00
|
|
|
import {URLSearchParams} from './url_search_params';
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* HTTP request body used by both {@link Request} and {@link Response}
|
|
|
|
* https://fetch.spec.whatwg.org/#body
|
|
|
|
*/
|
|
|
|
export abstract class Body {
|
|
|
|
/**
|
|
|
|
* @internal
|
|
|
|
*/
|
|
|
|
protected _body: any;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Attempts to return body as parsed `JSON` object, or raises an exception.
|
|
|
|
*/
|
|
|
|
json(): any {
|
2016-10-19 16:42:39 -04:00
|
|
|
if (typeof this._body === 'string') {
|
|
|
|
return JSON.parse(<string>this._body);
|
2016-05-26 18:47:20 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if (this._body instanceof ArrayBuffer) {
|
2016-10-19 16:42:39 -04:00
|
|
|
return JSON.parse(this.text());
|
2016-05-26 18:47:20 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return this._body;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the body as a string, presuming `toString()` can be called on the response body.
|
|
|
|
*/
|
|
|
|
text(): string {
|
|
|
|
if (this._body instanceof URLSearchParams) {
|
|
|
|
return this._body.toString();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this._body instanceof ArrayBuffer) {
|
|
|
|
return String.fromCharCode.apply(null, new Uint16Array(<ArrayBuffer>this._body));
|
|
|
|
}
|
|
|
|
|
2016-08-12 00:40:18 -04:00
|
|
|
if (this._body === null) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
2016-11-15 12:19:14 -05:00
|
|
|
if (typeof this._body === 'object') {
|
2016-10-19 16:42:39 -04:00
|
|
|
return JSON.stringify(this._body, null, 2);
|
2016-05-26 18:47:20 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return this._body.toString();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return the body as an ArrayBuffer
|
|
|
|
*/
|
|
|
|
arrayBuffer(): ArrayBuffer {
|
|
|
|
if (this._body instanceof ArrayBuffer) {
|
|
|
|
return <ArrayBuffer>this._body;
|
|
|
|
}
|
|
|
|
|
|
|
|
return stringToArrayBuffer(this.text());
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the request's body as a Blob, assuming that body exists.
|
|
|
|
*/
|
|
|
|
blob(): Blob {
|
|
|
|
if (this._body instanceof Blob) {
|
|
|
|
return <Blob>this._body;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this._body instanceof ArrayBuffer) {
|
|
|
|
return new Blob([this._body]);
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error('The request body isn\'t either a blob or an array buffer');
|
|
|
|
}
|
|
|
|
}
|