feat(http): refactor library to work in dart

Mostly internal refactoring needed to make ts2dart and DartAnalyzer happy.

Fixes #2415
This commit is contained in:
Jeff Cross
2015-06-19 12:14:12 -07:00
parent fa7da0ca5d
commit 55bf0e554f
26 changed files with 424 additions and 379 deletions

View File

@ -11,6 +11,8 @@ class Math {
static double random() => _random.nextDouble();
}
int ENUM_INDEX(value) => value.index;
class CONST {
const CONST();
}

View File

@ -31,6 +31,11 @@ _global.assert = function assert(condition) {
_global['assert'].call(condition);
}
};
export function ENUM_INDEX(value: int): int {
return value;
}
// This function is needed only to properly support Dart's const expressions
// see https://github.com/angular/ts2dart/pull/151 for more info
export function CONST_EXPR<T>(expr: T): T {

View File

@ -1,9 +1,11 @@
library angular2.src.http.backends.browser_xhr;
/// import 'dart:html' show HttpRequest;
/// import 'package:angular2/di.dart';
import 'dart:html' show HttpRequest;
import 'package:angular2/di.dart';
/// @Injectable()
/// class BrowserXHR {
/// factory BrowserXHR() => new HttpRequest();
/// }
@Injectable()
class BrowserXHR {
HttpRequest build() {
return new HttpRequest();
}
}

View File

@ -5,5 +5,6 @@ import {Injectable} from 'angular2/di';
// Make sure not to evaluate this in a non-browser environment!
@Injectable()
export class BrowserXHR {
constructor() { return <any>(new window.XMLHttpRequest()); }
constructor() {}
build(): any { return <any>(new window.XMLHttpRequest()); }
}

View File

@ -3,7 +3,9 @@ import {Request} from 'angular2/src/http/static_request';
import {Response} from 'angular2/src/http/static_response';
import {ReadyStates} from 'angular2/src/http/enums';
import {Connection, ConnectionBackend} from 'angular2/src/http/interfaces';
import * as Rx from 'rx';
import {ObservableWrapper, EventEmitter} from 'angular2/src/facade/async';
import {isPresent} from 'angular2/src/facade/lang';
import {IMPLEMENTS, BaseException} from 'angular2/src/facade/lang';
/**
*
@ -14,7 +16,8 @@ import * as Rx from 'rx';
* {@link MockBackend} in order to mock responses to requests.
*
**/
export class MockConnection implements Connection {
@IMPLEMENTS(Connection)
export class MockConnection {
// TODO Name `readyState` should change to be more generic, and states could be made to be more
// descriptive than XHR states.
/**
@ -33,18 +36,12 @@ export class MockConnection implements Connection {
* Observable](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md)
* of {@link Response}. Can be subscribed to in order to be notified when a response is available.
*/
response: Rx.Subject<Response>;
response: EventEmitter;
constructor(req: Request) {
if (Rx.hasOwnProperty('default')) {
this.response = new ((<any>Rx).default.Rx.Subject)();
} else {
this.response = new Rx.Subject<Response>();
}
this.response = new EventEmitter();
this.readyState = ReadyStates.OPEN;
this.request = req;
this.dispose = this.dispose.bind(this);
}
/**
@ -71,12 +68,12 @@ export class MockConnection implements Connection {
*
*/
mockRespond(res: Response) {
if (this.readyState >= ReadyStates.DONE) {
throw new Error('Connection has already been resolved');
if (this.readyState === ReadyStates.DONE || this.readyState === ReadyStates.CANCELLED) {
throw new BaseException('Connection has already been resolved');
}
this.readyState = ReadyStates.DONE;
this.response.onNext(res);
this.response.onCompleted();
ObservableWrapper.callNext(this.response, res);
ObservableWrapper.callReturn(this.response);
}
/**
@ -100,8 +97,8 @@ export class MockConnection implements Connection {
mockError(err?) {
// Matches XHR semantics
this.readyState = ReadyStates.DONE;
this.response.onError(err);
this.response.onCompleted();
ObservableWrapper.callThrow(this.response, err);
ObservableWrapper.callReturn(this.response);
}
}
@ -137,7 +134,8 @@ export class MockConnection implements Connection {
* This method only exists in the mock implementation, not in real Backends.
**/
@Injectable()
export class MockBackend implements ConnectionBackend {
@IMPLEMENTS(ConnectionBackend)
export class MockBackend {
/**
* [RxJS
* Subject](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/subject.md)
@ -171,7 +169,7 @@ export class MockBackend implements ConnectionBackend {
*
* This property only exists in the mock implementation, not in real Backends.
*/
connections: Rx.Subject<MockConnection>;
connections: EventEmitter; //<MockConnection>
/**
* An array representation of `connections`. This array will be updated with each connection that
@ -188,20 +186,14 @@ export class MockBackend implements ConnectionBackend {
*
* This property only exists in the mock implementation, not in real Backends.
*/
pendingConnections: Rx.Observable<MockConnection>;
pendingConnections: EventEmitter; //<MockConnection>
constructor() {
var Observable;
this.connectionsArray = [];
if (Rx.hasOwnProperty('default')) {
this.connections = new (<any>Rx).default.Rx.Subject();
Observable = (<any>Rx).default.Rx.Observable;
} else {
this.connections = new Rx.Subject<MockConnection>();
Observable = Rx.Observable;
}
this.connections.subscribe(connection => this.connectionsArray.push(connection));
this.pendingConnections =
Observable.fromArray(this.connectionsArray).filter((c) => c.readyState < ReadyStates.DONE);
this.connections = new EventEmitter();
ObservableWrapper.subscribe(this.connections,
connection => this.connectionsArray.push(connection));
this.pendingConnections = new EventEmitter();
// Observable.fromArray(this.connectionsArray).filter((c) => c.readyState < ReadyStates.DONE);
}
/**
@ -211,8 +203,8 @@ export class MockBackend implements ConnectionBackend {
*/
verifyNoPendingRequests() {
let pending = 0;
this.pendingConnections.subscribe((c) => pending++);
if (pending > 0) throw new Error(`${pending} pending connections to be resolved`);
ObservableWrapper.subscribe(this.pendingConnections, c => pending++);
if (pending > 0) throw new BaseException(`${pending} pending connections to be resolved`);
}
/**
@ -221,7 +213,7 @@ export class MockBackend implements ConnectionBackend {
*
* This method only exists in the mock implementation, not in real Backends.
*/
resolveAllConnections() { this.connections.subscribe((c) => c.readyState = 4); }
resolveAllConnections() { ObservableWrapper.subscribe(this.connections, c => c.readyState = 4); }
/**
* Creates a new {@link MockConnection}. This is equivalent to calling `new
@ -229,12 +221,12 @@ export class MockBackend implements ConnectionBackend {
* observable of this `MockBackend` instance. This method will usually only be used by tests
* against the framework itself, not by end-users.
*/
createConnection(req: Request): Connection {
if (!req || !(req instanceof Request)) {
throw new Error(`createConnection requires an instance of Request, got ${req}`);
createConnection(req: Request) {
if (!isPresent(req) || !(req instanceof Request)) {
throw new BaseException(`createConnection requires an instance of Request, got ${req}`);
}
let connection = new MockConnection(req);
this.connections.onNext(connection);
ObservableWrapper.callNext(this.connections, connection);
return connection;
}
}

View File

@ -1,11 +1,11 @@
import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods} from '../enums';
import {ReadyStates, RequestMethods, RequestMethodsMap} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {Inject} from 'angular2/di';
import {Injectable} from 'angular2/di';
import {BrowserXHR} from './browser_xhr';
import * as Rx from 'rx';
import {EventEmitter, ObservableWrapper} from 'angular2/src/facade/async';
import {isPresent, ENUM_INDEX} from 'angular2/src/facade/lang';
/**
* Creates connections using `XMLHttpRequest`. Given a fully-qualified
@ -22,22 +22,24 @@ export class XHRConnection implements Connection {
* [Subject](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/subject.md)
* which emits a single {@link Response} value on load event of `XMLHttpRequest`.
*/
response: Rx.Subject<Response>;
response: EventEmitter; //<Response>;
readyState: ReadyStates;
private _xhr;
constructor(req: Request, NativeConstruct: any) {
constructor(req: Request, browserXHR: BrowserXHR) {
// TODO: get rid of this when enum lookups are available in ts2dart
// https://github.com/angular/ts2dart/issues/221
var requestMethodsMap = new RequestMethodsMap();
this.request = req;
if (Rx.hasOwnProperty('default')) {
this.response = new (<any>Rx).default.Rx.Subject();
} else {
this.response = new Rx.Subject<Response>();
}
this._xhr = new NativeConstruct();
this.response = new EventEmitter();
this._xhr = browserXHR.build();
// TODO(jeffbcross): implement error listening/propagation
this._xhr.open(RequestMethods[req.method], req.url);
this._xhr.open(requestMethodsMap.getMethod(ENUM_INDEX(req.method)), req.url);
this._xhr.addEventListener(
'load',
() => {this.response.onNext(new Response(this._xhr.response || this._xhr.responseText))});
(_) => {ObservableWrapper.callNext(
this.response, new Response({
body: isPresent(this._xhr.response) ? this._xhr.response : this._xhr.responseText
}))});
// TODO(jeffbcross): make this more dynamic based on body type
this._xhr.send(this.request.text());
}
@ -76,8 +78,8 @@ export class XHRConnection implements Connection {
**/
@Injectable()
export class XHRBackend implements ConnectionBackend {
constructor(private _NativeConstruct: BrowserXHR) {}
constructor(private _browserXHR: BrowserXHR) {}
createConnection(request: Request): XHRConnection {
return new XHRConnection(request, this._NativeConstruct);
return new XHRConnection(request, this._browserXHR);
}
}

View File

@ -1,11 +1,11 @@
import {CONST_EXPR, CONST, isPresent} from 'angular2/src/facade/lang';
import {Headers} from './headers';
import {URLSearchParams} from './url_search_params';
import {RequestModesOpts, RequestMethods, RequestCacheOpts, RequestCredentialsOpts} from './enums';
import {IRequestOptions} from './interfaces';
import {Injectable} from 'angular2/di';
import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {ListWrapper, StringMapWrapper, StringMap} from 'angular2/src/facade/collection';
const INITIALIZER = CONST_EXPR({});
/**
* Creates a request options object with default properties as described in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#requestinit) to be optionally provided when instantiating a
@ -28,28 +28,49 @@ export class RequestOptions implements IRequestOptions {
/**
* Body to be used when creating the request.
*/
body: URLSearchParams | FormData | Blob | string;
// TODO: support FormData, Blob, URLSearchParams, JSON
body: string;
mode: RequestModesOpts = RequestModesOpts.Cors;
credentials: RequestCredentialsOpts;
cache: RequestCacheOpts;
constructor({method, headers, body, mode, credentials, cache}: IRequestOptions = {
method: RequestMethods.GET,
mode: RequestModesOpts.Cors
}) {
this.method = method;
url: string;
constructor({method, headers, body, mode, credentials, cache, url}: IRequestOptions = {}) {
this.method = isPresent(method) ? method : RequestMethods.GET;
this.headers = headers;
this.body = body;
this.mode = mode;
this.mode = isPresent(mode) ? mode : RequestModesOpts.Cors;
this.credentials = credentials;
this.cache = cache;
this.url = url;
}
/**
* Creates a copy of the `RequestOptions` instance, using the optional input as values to override
* existing values.
*/
merge(opts: IRequestOptions = {}): RequestOptions {
return new RequestOptions(StringMapWrapper.merge(this, opts));
merge({url = null, method = null, headers = null, body = null, mode = null, credentials = null,
cache = null}: any = {}): RequestOptions {
return new RequestOptions({
method: isPresent(method) ? method : this.method,
headers: isPresent(headers) ? headers : this.headers,
body: isPresent(body) ? body : this.body,
mode: isPresent(mode) ? mode : this.mode,
credentials: isPresent(credentials) ? credentials : this.credentials,
cache: isPresent(cache) ? cache : this.cache,
url: isPresent(url) ? url : this.url
});
}
static fromStringWrapper(map: StringMap<string, any>): RequestOptions {
return new RequestOptions({
method: StringMapWrapper.get(map, 'method'),
headers: StringMapWrapper.get(map, 'headers'),
body: StringMapWrapper.get(map, 'body'),
mode: StringMapWrapper.get(map, 'mode'),
credentials: StringMapWrapper.get(map, 'credentials'),
cache: StringMapWrapper.get(map, 'cache'),
url:<string>StringMapWrapper.get(map, 'url')
})
}
}

View File

@ -3,21 +3,19 @@ import {ResponseTypes} from './enums';
import {ResponseOptions} from './interfaces';
export class BaseResponseOptions implements ResponseOptions {
body: string | Object | ArrayBuffer | JSON | FormData | Blob;
status: number;
headers: Headers | Object;
headers: Headers;
statusText: string;
type: ResponseTypes;
url: string;
constructor({status = 200, statusText = 'Ok', type = ResponseTypes.Default,
headers = new Headers(), url = ''}: ResponseOptions = {}) {
this.status = status;
this.statusText = statusText;
this.type = type;
this.headers = headers;
this.url = url;
constructor() {
this.status = 200;
this.statusText = 'Ok';
this.type = ResponseTypes.Default;
this.headers = new Headers();
}
}
;
export var baseResponseOptions = Object.freeze(new BaseResponseOptions());
export var baseResponseOptions = new BaseResponseOptions();

View File

@ -1,3 +1,5 @@
import {StringMap, StringMapWrapper} from 'angular2/src/facade/collection';
export enum RequestModesOpts {
Cors,
NoCors,
@ -29,6 +31,14 @@ export enum RequestMethods {
PATCH
}
// TODO: Remove this when enum lookups are available in ts2dart
// https://github.com/angular/ts2dart/issues/221
export class RequestMethodsMap {
private _methods: List<string>;
constructor() { this._methods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'HEAD', 'PATCH']; }
getMethod(method: int): string { return this._methods[method]; }
}
export enum ReadyStates {
UNSENT,
OPEN,

View File

@ -11,7 +11,8 @@ import {
List,
Map,
MapWrapper,
ListWrapper
ListWrapper,
StringMap
} from 'angular2/src/facade/collection';
/**
@ -21,15 +22,15 @@ import {
*/
export class Headers {
_headersMap: Map<string, List<string>>;
constructor(headers?: Headers | Object) {
constructor(headers?: Headers | StringMap<string, any>) {
if (isBlank(headers)) {
this._headersMap = new Map();
return;
}
if (isPresent((<Headers>headers)._headersMap)) {
if (headers instanceof Headers) {
this._headersMap = (<Headers>headers)._headersMap;
} else if (isJsObject(headers)) {
} else if (headers instanceof StringMap) {
this._headersMap = MapWrapper.createFromStringMap(headers);
MapWrapper.forEach(this._headersMap, (v, k) => {
if (!isListLikeIterable(v)) {
@ -42,7 +43,8 @@ export class Headers {
}
append(name: string, value: string): void {
var list = this._headersMap.get(name) || [];
var mapName = this._headersMap.get(name);
var list = isListLikeIterable(mapName) ? mapName : [];
list.push(value);
this._headersMap.set(name, list);
}
@ -57,13 +59,19 @@ export class Headers {
keys(): List<string> { return MapWrapper.keys(this._headersMap); }
// TODO: this implementation seems wrong. create list then check if it's iterable?
set(header: string, value: string | List<string>): void {
var list = [];
if (!isListLikeIterable(value)) {
list.push(value);
var isDart = false;
// Dart hack
if (list.toString().length === 2) {
isDart = true;
}
if (isListLikeIterable(value)) {
var pushValue = (<List<string>>value).toString();
if (isDart) pushValue = pushValue.substring(1, pushValue.length - 1);
list.push(pushValue);
} else {
list.push(ListWrapper.toString((<List<string>>value)));
list.push(value);
}
this._headersMap.set(header, list);
@ -71,7 +79,10 @@ export class Headers {
values(): List<List<string>> { return MapWrapper.values(this._headersMap); }
getAll(header: string): Array<string> { return this._headersMap.get(header) || []; }
getAll(header: string): Array<string> {
var headers = this._headersMap.get(header);
return isListLikeIterable(headers) ? headers : [];
}
entries() { throw new BaseException('"entries" method is not implemented on Headers class'); }
}

View File

@ -1,24 +1,25 @@
/// <reference path="../../typings/rx/rx.d.ts" />
import {isString, isPresent, isBlank} from 'angular2/src/facade/lang';
import {Injectable} from 'angular2/src/di/decorators';
import {IRequestOptions, Connection, IHttp} from './interfaces';
import {IRequestOptions, Connection, ConnectionBackend} from './interfaces';
import {Request} from './static_request';
import {Response} from './static_response';
import {XHRBackend} from './backends/xhr_backend';
import {BaseRequestOptions} from './base_request_options';
import {BaseRequestOptions, RequestOptions} from './base_request_options';
import {RequestMethods} from './enums';
import {URLSearchParams} from './url_search_params';
import * as Rx from 'rx';
import {EventEmitter} from 'angular2/src/facade/async';
function httpRequest(backend: XHRBackend, request: Request): Rx.Observable<Response> {
return <Rx.Observable<Response>>(Observable.create(observer => {
var connection: Connection = backend.createConnection(request);
var internalSubscription = connection.response.subscribe(observer);
return () => {
internalSubscription.dispose();
connection.dispose();
};
}));
function httpRequest(backend: ConnectionBackend, request: Request): EventEmitter {
return backend.createConnection(request).response;
}
function mergeOptions(defaultOpts, providedOpts, method, url): RequestOptions {
var newOptions = defaultOpts;
if (isPresent(providedOpts)) {
newOptions = newOptions.merge(providedOpts);
}
if (isPresent(method)) {
return newOptions.merge({method: method, url: url});
} else {
return newOptions.merge({url: url});
}
}
/**
@ -72,7 +73,7 @@ function httpRequest(backend: XHRBackend, request: Request): Rx.Observable<Respo
**/
@Injectable()
export class Http {
constructor(private _backend: XHRBackend, private _defaultOptions: BaseRequestOptions) {}
constructor(private _backend: ConnectionBackend, private _defaultOptions: BaseRequestOptions) {}
/**
* Performs any type of http request. First argument is required, and can either be a url or
@ -80,77 +81,70 @@ export class Http {
* object can be provided as the 2nd argument. The options object will be merged with the values
* of {@link BaseRequestOptions} before performing the request.
*/
request(url: string | Request, options?: IRequestOptions): Rx.Observable<Response> {
if (typeof url === 'string') {
return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options)));
request(url: string | Request, options?: IRequestOptions): EventEmitter {
var responseObservable: EventEmitter;
if (isString(url)) {
responseObservable = httpRequest(
this._backend,
new Request(mergeOptions(this._defaultOptions, options, RequestMethods.GET, url)));
} else if (url instanceof Request) {
return httpRequest(this._backend, url);
responseObservable = httpRequest(this._backend, url);
}
return responseObservable;
}
/**
* Performs a request with `get` http method.
*/
get(url: string, options?: IRequestOptions): Rx.Observable<Response> {
return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options)
.merge({method: RequestMethods.GET})));
get(url: string, options?: IRequestOptions) {
return httpRequest(this._backend, new Request(mergeOptions(this._defaultOptions, options,
RequestMethods.GET, url)));
}
/**
* Performs a request with `post` http method.
*/
post(url: string, body: URLSearchParams | FormData | Blob | string,
options?: IRequestOptions): Rx.Observable<Response> {
post(url: string, body: string, options?: IRequestOptions) {
return httpRequest(this._backend,
new Request(url, this._defaultOptions.merge(options)
.merge({body: body, method: RequestMethods.POST})));
new Request(mergeOptions(this._defaultOptions.merge({body: body}), options,
RequestMethods.POST, url)));
}
/**
* Performs a request with `put` http method.
*/
put(url: string, body: URLSearchParams | FormData | Blob | string,
options?: IRequestOptions): Rx.Observable<Response> {
put(url: string, body: string, options?: IRequestOptions) {
return httpRequest(this._backend,
new Request(url, this._defaultOptions.merge(options)
.merge({body: body, method: RequestMethods.PUT})));
new Request(mergeOptions(this._defaultOptions.merge({body: body}), options,
RequestMethods.PUT, url)));
}
/**
* Performs a request with `delete` http method.
*/
delete (url: string, options?: IRequestOptions): Rx.Observable<Response> {
return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options).merge(
{method: RequestMethods.DELETE})));
delete (url: string, options?: IRequestOptions) {
return httpRequest(this._backend, new Request(mergeOptions(this._defaultOptions, options,
RequestMethods.DELETE, url)));
}
/**
* Performs a request with `patch` http method.
*/
patch(url: string, body: URLSearchParams | FormData | Blob | string,
options?: IRequestOptions): Rx.Observable<Response> {
patch(url: string, body: string, options?: IRequestOptions) {
return httpRequest(this._backend,
new Request(url, this._defaultOptions.merge(options)
.merge({body: body, method: RequestMethods.PATCH})));
new Request(mergeOptions(this._defaultOptions.merge({body: body}), options,
RequestMethods.PATCH, url)));
}
/**
* Performs a request with `head` http method.
*/
head(url: string, options?: IRequestOptions): Rx.Observable<Response> {
return httpRequest(this._backend, new Request(url, this._defaultOptions.merge(options)
.merge({method: RequestMethods.HEAD})));
head(url: string, options?: IRequestOptions) {
return httpRequest(this._backend, new Request(mergeOptions(this._defaultOptions, options,
RequestMethods.HEAD, url)));
}
}
var Observable;
if (Rx.hasOwnProperty('default')) {
Observable = (<any>Rx).default.Rx.Observable;
} else {
Observable = Rx.Observable;
}
/**
*
* Alias to the `request` method of {@link Http}, for those who'd prefer a simple function instead
@ -174,10 +168,10 @@ if (Rx.hasOwnProperty('default')) {
* }
* ```
**/
export function HttpFactory(backend: XHRBackend, defaultOptions: BaseRequestOptions): IHttp {
export function HttpFactory(backend: ConnectionBackend, defaultOptions: BaseRequestOptions) {
return function(url: string | Request, options?: IRequestOptions) {
if (typeof url === 'string') {
return httpRequest(backend, new Request(url, defaultOptions.merge(options)));
if (isString(url)) {
return httpRequest(backend, new Request(mergeOptions(defaultOptions, options, null, url)));
} else if (url instanceof Request) {
return httpRequest(backend, url);
}

View File

@ -9,24 +9,36 @@ import {
ResponseTypes
} from './enums';
import {Headers} from './headers';
import {URLSearchParams} from './url_search_params';
import {BaseException} from 'angular2/src/facade/lang';
import {EventEmitter} from 'angular2/src/facade/async';
import {Request} from './static_request';
export class ConnectionBackend {
constructor() {}
createConnection(request: any): Connection { throw new BaseException('Abstract!'); }
}
export class Connection {
readyState: ReadyStates;
request: Request;
response: EventEmitter; //<IResponse>;
dispose(): void { throw new BaseException('Abstract!'); }
}
export interface IRequestOptions {
url?: string;
method?: RequestMethods;
headers?: Headers;
body?: URLSearchParams | FormData | Blob | string;
// TODO: Support Blob, ArrayBuffer, JSON, URLSearchParams, FormData
body?: string;
mode?: RequestModesOpts;
credentials?: RequestCredentialsOpts;
cache?: RequestCacheOpts;
}
export interface IRequest {
method: RequestMethods;
mode: RequestModesOpts;
credentials: RequestCredentialsOpts;
}
export interface ResponseOptions {
// TODO: Support Blob, ArrayBuffer, JSON
body?: string | Object | FormData;
status?: number;
statusText?: string;
headers?: Headers | Object;
@ -43,23 +55,12 @@ export interface IResponse {
url: string;
totalBytes: number;
bytesLoaded: number;
blob(): Blob;
arrayBuffer(): ArrayBuffer;
blob(): any; // TODO: Blob
arrayBuffer(): any; // TODO: ArrayBuffer
text(): string;
json(): Object;
}
export interface ConnectionBackend {
createConnection(observer: any, config: IRequest): Connection;
}
export interface Connection {
readyState: ReadyStates;
request: IRequest;
response: Rx.Subject<IResponse>;
dispose(): void;
}
/**
* Provides an interface to provide type information for {@link HttpFactory} when injecting.
*
@ -83,4 +84,4 @@ export interface Connection {
*/
// Prefixed as IHttp because used in conjunction with Http class, but interface is callable
// constructor(@Inject(Http) http:IHttp)
export interface IHttp { (url: string, options?: IRequestOptions): Rx.Observable<IResponse> }
export interface IHttp { (url: string, options?: IRequestOptions): EventEmitter }

View File

@ -1,8 +1,9 @@
import {RequestMethods, RequestModesOpts, RequestCredentialsOpts} from './enums';
import {URLSearchParams} from './url_search_params';
import {IRequestOptions, IRequest} from './interfaces';
import {RequestMethods, RequestModesOpts, RequestCredentialsOpts, RequestCacheOpts} from './enums';
import {RequestOptions} from './base_request_options';
import {IRequestOptions} from './interfaces';
import {Headers} from './headers';
import {BaseException, RegExpWrapper} from 'angular2/src/facade/lang';
import {BaseException, RegExpWrapper, CONST_EXPR, isPresent} from 'angular2/src/facade/lang';
import {StringMap, StringMapWrapper} from 'angular2/src/facade/collection';
// TODO(jeffbcross): properly implement body accessors
/**
@ -13,7 +14,7 @@ import {BaseException, RegExpWrapper} from 'angular2/src/facade/lang';
* but is considered a static value whose body can be accessed many times. There are other
* differences in the implementation, but this is the most significant.
*/
export class Request implements IRequest {
export class Request {
/**
* Http method with which to perform the request.
*
@ -27,22 +28,27 @@ export class Request implements IRequest {
* Spec](https://fetch.spec.whatwg.org/#headers-class). {@link Headers} class reference.
*/
headers: Headers;
/** Url of the remote resource */
url: string;
// TODO: support URLSearchParams | FormData | Blob | ArrayBuffer
private _body: string;
cache: RequestCacheOpts;
// TODO(jeffbcross): determine way to add type to destructured args
constructor(options?: IRequestOptions) {
var requestOptions: RequestOptions = options instanceof
StringMap ? RequestOptions.fromStringWrapper(<StringMap<string, any>>options) :
<RequestOptions>options;
private _body: URLSearchParams | FormData | Blob | string;
constructor(/** Url of the remote resource */ public url: string,
{body, method = RequestMethods.GET, mode = RequestModesOpts.Cors,
credentials = RequestCredentialsOpts.Omit,
headers = new Headers()}: IRequestOptions = {}) {
this._body = body;
this.method = method;
// Defaults to 'cors', consistent with browser
this.url = requestOptions.url;
this._body = requestOptions.body;
this.method = requestOptions.method;
// TODO(jeffbcross): implement behavior
this.mode = mode;
this.mode = requestOptions.mode;
// Defaults to 'omit', consistent with browser
// TODO(jeffbcross): implement behavior
this.credentials = credentials;
this.headers = headers;
this.credentials = requestOptions.credentials;
this.headers = requestOptions.headers;
this.cache = requestOptions.cache;
}
/**
@ -50,5 +56,5 @@ export class Request implements IRequest {
* empty
* string.
*/
text(): String { return this._body ? this._body.toString() : ''; }
text(): String { return isPresent(this._body) ? this._body.toString() : ''; }
}

View File

@ -1,7 +1,7 @@
import {IResponse, ResponseOptions} from './interfaces';
import {ResponseTypes} from './enums';
import {baseResponseOptions} from './base_response_options';
import {BaseException, isJsObject, isString, global} from 'angular2/src/facade/lang';
import {BaseException, isJsObject, isString, isPresent, Json} from 'angular2/src/facade/lang';
import {Headers} from './headers';
// TODO: make this injectable so baseResponseOptions can be overridden, mostly for the benefit of
@ -72,34 +72,37 @@ export class Response implements IResponse {
* Spec](https://fetch.spec.whatwg.org/#headers-class).
*/
headers: Headers;
constructor(private _body?: string | Object | ArrayBuffer | JSON | FormData | Blob,
{status, statusText, headers, type, url}: ResponseOptions = baseResponseOptions) {
// TODO: Support ArrayBuffer, JSON, FormData, Blob
private _body: string | Object;
constructor({body, status, statusText, headers, type, url}: ResponseOptions = {}) {
if (isJsObject(headers)) {
headers = new Headers(headers);
}
this.status = status;
this.statusText = statusText;
this.headers = <Headers>headers;
this.type = type;
this.url = url;
this._body = isPresent(body) ? body : baseResponseOptions.body;
this.status = isPresent(status) ? status : baseResponseOptions.status;
this.statusText = isPresent(statusText) ? statusText : baseResponseOptions.statusText;
this.headers = isPresent(headers) ? <Headers>headers : baseResponseOptions.headers;
this.type = isPresent(type) ? type : baseResponseOptions.type;
this.url = isPresent(url) ? url : baseResponseOptions.url;
}
/**
* Not yet implemented
*/
blob(): Blob {
throw new BaseException('"blob()" method not implemented on Response superclass');
}
// 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.
*/
json(): JSON {
json(): Object {
var jsonResponse;
if (isJsObject(this._body)) {
return <JSON>this._body;
jsonResponse = this._body;
} else if (isString(this._body)) {
return global.JSON.parse(<string>this._body);
jsonResponse = Json.parse(<string>this._body);
}
return jsonResponse;
}
/**
@ -110,7 +113,8 @@ export class Response implements IResponse {
/**
* Not yet implemented
*/
arrayBuffer(): ArrayBuffer {
// TODO: ArrayBuffer return type
arrayBuffer(): any {
throw new BaseException('"arrayBuffer()" method not implemented on Response superclass');
}
}

View File

@ -1,14 +1,20 @@
import {isPresent, isBlank, StringWrapper} from 'angular2/src/facade/lang';
import {Map, MapWrapper, List, ListWrapper} from 'angular2/src/facade/collection';
import {
Map,
MapWrapper,
List,
ListWrapper,
isListLikeIterable
} from 'angular2/src/facade/collection';
function paramParser(rawParams: string): Map<string, List<string>> {
var map: Map<string, List<string>> = new Map();
var params: List<string> = StringWrapper.split(rawParams, '&');
var params: List<string> = StringWrapper.split(rawParams, new RegExp('&'));
ListWrapper.forEach(params, (param: string) => {
var split: List<string> = StringWrapper.split(param, '=');
var split: List<string> = StringWrapper.split(param, new RegExp('='));
var key = ListWrapper.get(split, 0);
var val = ListWrapper.get(split, 1);
var list = map.get(key) || [];
var list = isPresent(map.get(key)) ? map.get(key) : [];
list.push(val);
map.set(key, list);
});
@ -21,12 +27,23 @@ export class URLSearchParams {
has(param: string): boolean { return this.paramsMap.has(param); }
get(param: string): string { return ListWrapper.first(this.paramsMap.get(param)); }
get(param: string): string {
var storedParam = this.paramsMap.get(param);
if (isListLikeIterable(storedParam)) {
return ListWrapper.first(storedParam);
} else {
return null;
}
}
getAll(param: string): List<string> { return this.paramsMap.get(param) || []; }
getAll(param: string): List<string> {
var mapParam = this.paramsMap.get(param);
return isPresent(mapParam) ? mapParam : [];
}
append(param: string, val: string): void {
var list = this.paramsMap.get(param) || [];
var mapParam = this.paramsMap.get(param);
var list = isPresent(mapParam) ? mapParam : [];
list.push(val);
this.paramsMap.set(param, list);
}