From 4f0803c5aa7d43540fa8ed4b9cb4aacbdb10ac2d Mon Sep 17 00:00:00 2001 From: Victor Date: Fri, 7 Feb 2014 16:25:00 +0100 Subject: [PATCH 1/2] style(http): code cleanup --- lib/core_dom/http.dart | 235 +++++++++++++++++-------------------- lib/mock/http_backend.dart | 209 ++++++++++++++------------------- 2 files changed, 196 insertions(+), 248 deletions(-) diff --git a/lib/core_dom/http.dart b/lib/core_dom/http.dart index 6adeb2ff4..abcd91c6c 100644 --- a/lib/core_dom/http.dart +++ b/lib/core_dom/http.dart @@ -33,7 +33,7 @@ class HttpBackend { mimeType: mimeType, requestHeaders: requestHeaders, sendData: sendData, - onProgress: onProgress).then((x) => c.complete(x), + onProgress: onProgress).then((x) => c.complete(x), onError: (e, stackTrace) => c.completeError(e, stackTrace)); return c.future; } @@ -62,9 +62,8 @@ class HttpInterceptor { /** * All parameters are optional. */ - HttpInterceptor({ - this.request, this.response, - this.requestError, this.responseError}); + HttpInterceptor({this.request, this.response, this.requestError, + this.responseError}); } @@ -79,7 +78,8 @@ class HttpInterceptor { */ class DefaultTransformDataHttpInterceptor implements HttpInterceptor { Function request = (HttpResponseConfig config) { - if (config.data != null && config.data is! String && config.data is! dom.File) { + if (config.data != null && config.data is! String && + config.data is! dom.File) { config.data = JSON.encode(config.data); } return config; @@ -90,8 +90,7 @@ class DefaultTransformDataHttpInterceptor implements HttpInterceptor { static var _PROTECTION_PREFIX = new RegExp('^\\)\\]\\}\',?\\n'); Function response = (HttpResponse r) { if (r.data is String) { - var d = r.data; - d = d.replaceFirst(_PROTECTION_PREFIX, ''); + var d = r.data.replaceFirst(_PROTECTION_PREFIX, ''); if (d.contains(_JSON_START) && d.contains(_JSON_END)) { d = JSON.decode(d); } @@ -108,7 +107,8 @@ class DefaultTransformDataHttpInterceptor implements HttpInterceptor { */ @NgInjectableService() class HttpInterceptors { - List _interceptors = [new DefaultTransformDataHttpInterceptor()]; + List _interceptors = + [new DefaultTransformDataHttpInterceptor()]; add(HttpInterceptor x) => _interceptors.add(x); addAll(List x) => _interceptors.addAll(x); @@ -119,12 +119,13 @@ class HttpInterceptors { constructChain(List chain) { _interceptors.reversed.forEach((HttpInterceptor i) { // AngularJS has an optimization of not including null interceptors. - chain.insert(0, [ - i.request == null ? (x) => x : i.request, - i.requestError]); - chain.add([ - i.response == null ? (x) => x : i.response, - i.responseError]); + chain + ..insert(0, [ + i.request == null ? (x) => x : i.request, + i.requestError]) + ..add([ + i.response == null ? (x) => x : i.response, + i.responseError]); }); } @@ -136,7 +137,8 @@ class HttpInterceptors { } /** - * Creates a [HttpInterceptors] from a [List]. Does not include the default interceptors. + * Creates a [HttpInterceptors] from a [List]. Does not include the default + * interceptors. */ HttpInterceptors.of([List interceptors]) { _interceptors = interceptors; @@ -228,12 +230,10 @@ class HttpResponse { /** * The response's headers. Without parameters, this method will return the - * [Map] of headers. With [key] parameter, this method will return the specific - * header. + * [Map] of headers. With [key] parameter, this method will return the + * specific header. */ - headers([String key]) { - return key == null ? _headers : _headers[key]; - } + headers([String key]) => key == null ? _headers : _headers[key]; /** * Useful for debugging. @@ -246,20 +246,12 @@ class HttpResponse { */ @NgInjectableService() class HttpDefaultHeaders { - static String _defaultContentType = 'application/json;charset=utf-8'; - Map _headers = { - 'COMMON': { - 'Accept': 'application/json, text/plain, */*' - }, - 'POST' : { - 'Content-Type': _defaultContentType - }, - 'PUT' : { - 'Content-Type': _defaultContentType - }, - 'PATCH' : { - 'Content-Type': _defaultContentType - } + static var _defaultContentType = 'application/json;charset=utf-8'; + var _headers = { + 'COMMON': {'Accept': 'application/json, text/plain, */*'}, + 'POST' : {'Content-Type': _defaultContentType}, + 'PUT' : {'Content-Type': _defaultContentType }, + 'PATCH' : {'Content-Type': _defaultContentType} }; _applyHeaders(method, ucHeaders, headers) { @@ -288,9 +280,7 @@ class HttpDefaultHeaders { * Passing 'common' as [method] will return a Map that contains headers * common to all operations. */ - operator[](method) { - return _headers[method.toUpperCase()]; - } + operator[](method) => _headers[method.toUpperCase()]; } /** @@ -331,8 +321,8 @@ class HttpDefaults { } /** - * The [Http] service facilitates communication with the remote HTTP servers. It - * uses dart:html's [HttpRequest] and provides a number of features on top + * The [Http] service facilitates communication with the remote HTTP servers. + * It uses dart:html's [HttpRequest] and provides a number of features on top * of the core Dart library. * * For unit testing, applications should use the [MockHttpBackend] service. @@ -343,12 +333,12 @@ class HttpDefaults { * * http(method: 'GET', url: '/someUrl') * .then((HttpResponse response) { .. }, - * onError: (HttpRequest request) { .. }); + * onError: (HttpRequest request) { .. }); * * A response status code between 200 and 299 is considered a success status and - * will result in the 'then' being called. Note that if the response is a redirect, - * Dart's [HttpRequest] will transparently follow it, meaning that the error callback will not be - * called for such responses. + * will result in the 'then' being called. Note that if the response is a + * redirect, Dart's [HttpRequest] will transparently follow it, meaning that the + * error callback will not be called for such responses. * * # Shortcut methods * @@ -389,7 +379,7 @@ class HttpDefaults { */ @NgInjectableService() class Http { - Map> _pendingRequests = >{}; + var _pendingRequests = >{}; BrowserCookies _cookies; LocationWrapper _location; UrlRewriter _rewriter; @@ -404,31 +394,27 @@ class Http { /** * Constructor, useful for DI. */ - Http(this._cookies, this._location, this._rewriter, this._backend, this.defaults, this._interceptors); + Http(this._cookies, this._location, this._rewriter, this._backend, + this.defaults, this._interceptors); /** * DEPRECATED */ - async.Future getString(String url, - {bool withCredentials, void onProgress(dom.ProgressEvent e), Cache cache}) { - return request(url, - withCredentials: withCredentials, - onProgress: onProgress, - cache: cache).then((HttpResponse xhr) => xhr.responseText); - } + async.Future getString(String url, {bool withCredentials, + void onProgress(dom.ProgressEvent e), Cache cache}) => + request(url, + withCredentials: withCredentials, + onProgress: onProgress, + cache: cache).then((HttpResponse xhr) => xhr.responseText); /** - * Parse a request URL and determine whether this is a same-origin request as the application document. - * - * @param {string|Uri} requestUrl The url of the request as a string that will be resolved - * or a parsed URL object. - * @returns {boolean} Whether the request is for the same origin as the application document. + * Parse a [requestUrl] and determine whether this is a same-origin request as + * the application document. */ - _urlIsSameOrigin(String requestUrl) { + bool _urlIsSameOrigin(String requestUrl) { Uri originUrl = Uri.parse(_location.location.toString()); Uri parsed = originUrl.resolve(requestUrl); - return (parsed.scheme == originUrl.scheme && - parsed.host == originUrl.host); + return (parsed.scheme == originUrl.scheme && parsed.host == originUrl.host); } /** @@ -468,39 +454,39 @@ class Http { method = method.toUpperCase(); - if (headers == null) { headers = {}; } + if (headers == null) headers = {}; defaults.headers.setHeaders(headers, method); var xsrfValue = _urlIsSameOrigin(url) ? - _cookies[xsrfCookieName != null ? xsrfCookieName : defaults.xsrfCookieName] : null; + _cookies[xsrfCookieName != null ? xsrfCookieName : defaults.xsrfCookieName] : + null; if (xsrfValue != null) { - headers[xsrfHeaderName != null ? xsrfHeaderName : defaults.xsrfHeaderName] = xsrfValue; + headers[xsrfHeaderName != null ? xsrfHeaderName : defaults.xsrfHeaderName] + = xsrfValue; } // Check for functions in headers - headers.forEach((k,v) { - if (v is Function) { - headers[k] = v(); - } + headers.forEach((k, v) { + if (v is Function) headers[k] = v(); }); var serverRequest = (HttpResponseConfig config) { - assert(config.data == null || config.data is String || config.data is dom.File); + assert(config.data == null || config.data is String || + config.data is dom.File); // Strip content-type if data is undefined if (config.data == null) { new List.from(headers.keys) - .where((h) => h.toUpperCase() == 'CONTENT-TYPE') - .forEach((h) => headers.remove(h)); + .where((h) => h.toUpperCase() == 'CONTENT-TYPE') + .forEach((h) => headers.remove(h)); } - return request( - null, - config: config, - method: method, - sendData: config.data, - requestHeaders: config.headers, - cache: cache); + return request(null, + config: config, + method: method, + sendData: config.data, + requestHeaders: config.headers, + cache: cache); }; var chain = [[serverRequest, null]]; @@ -541,9 +527,9 @@ class Http { interceptors, cache, timeout - }) => call(method: 'GET', url: url, data: data, params: params, headers: headers, - xsrfHeaderName: xsrfHeaderName, xsrfCookieName: xsrfCookieName, - interceptors: interceptors, + }) => call(method: 'GET', url: url, data: data, params: params, + headers: headers, xsrfHeaderName: xsrfHeaderName, + xsrfCookieName: xsrfCookieName, interceptors: interceptors, cache: cache, timeout: timeout); /** @@ -559,9 +545,9 @@ class Http { interceptors, cache, timeout - }) => call(method: 'DELETE', url: url, data: data, params: params, headers: headers, - xsrfHeaderName: xsrfHeaderName, xsrfCookieName: xsrfCookieName, - interceptors: interceptors, + }) => call(method: 'DELETE', url: url, data: data, params: params, + headers: headers, xsrfHeaderName: xsrfHeaderName, + xsrfCookieName: xsrfCookieName, interceptors: interceptors, cache: cache, timeout: timeout); /** @@ -577,9 +563,9 @@ class Http { interceptors, cache, timeout - }) => call(method: 'HEAD', url: url, data: data, params: params, headers: headers, - xsrfHeaderName: xsrfHeaderName, xsrfCookieName: xsrfCookieName, - interceptors: interceptors, + }) => call(method: 'HEAD', url: url, data: data, params: params, + headers: headers, xsrfHeaderName: xsrfHeaderName, + xsrfCookieName: xsrfCookieName, interceptors: interceptors, cache: cache, timeout: timeout); /** @@ -594,9 +580,9 @@ class Http { interceptors, cache, timeout - }) => call(method: 'PUT', url: url, data: data, params: params, headers: headers, - xsrfHeaderName: xsrfHeaderName, xsrfCookieName: xsrfCookieName, - interceptors: interceptors, + }) => call(method: 'PUT', url: url, data: data, params: params, + headers: headers, xsrfHeaderName: xsrfHeaderName, + xsrfCookieName: xsrfCookieName, interceptors: interceptors, cache: cache, timeout: timeout); /** @@ -611,9 +597,9 @@ class Http { interceptors, cache, timeout - }) => call(method: 'POST', url: url, data: data, params: params, headers: headers, - xsrfHeaderName: xsrfHeaderName, xsrfCookieName: xsrfCookieName, - interceptors: interceptors, + }) => call(method: 'POST', url: url, data: data, params: params, + headers: headers, xsrfHeaderName: xsrfHeaderName, + xsrfCookieName: xsrfCookieName, interceptors: interceptors, cache: cache, timeout: timeout); /** @@ -629,9 +615,9 @@ class Http { interceptors, cache, timeout - }) => call(method: 'JSONP', url: url, data: data, params: params, headers: headers, - xsrfHeaderName: xsrfHeaderName, xsrfCookieName: xsrfCookieName, - interceptors: interceptors, + }) => call(method: 'JSONP', url: url, data: data, params: params, + headers: headers, xsrfHeaderName: xsrfHeaderName, + xsrfCookieName: xsrfCookieName, interceptors: interceptors, cache: cache, timeout: timeout); /** @@ -648,14 +634,10 @@ class Http { var i = line.indexOf(':'); if (i == -1) return; var key = line.substring(0, i).trim().toLowerCase(); - var val = line.substring(i + 1).trim(); - - if (key != '') { - if (parsed.containsKey(key)) { - parsed[key] += ', ' + val; - } else { - parsed[key] = val; - } + + if (key.isNotEmpty) { + var val = line.substring(i + 1).trim(); + parsed[key] = parsed.containsKey(key) ? "${parsed[key]}, $val" : val; } }); return parsed; @@ -666,7 +648,7 @@ class Http { * that the [Http] service is currently waiting for. */ Iterable > get pendingRequests => - _pendingRequests.values; + _pendingRequests.values; /** * DEPRECATED @@ -690,7 +672,7 @@ class Http { url = _buildUrl(config.url, config.params); } - if (cache is bool && cache == false) { + if (cache == false) { cache = null; } else if (cache == null) { cache = defaults.cache; @@ -699,9 +681,11 @@ class Http { if (cache != null && _pendingRequests.containsKey(url)) { return _pendingRequests[url]; } - var cachedValue = (cache != null && method == 'GET') ? cache.get(url) : null; - if (cachedValue != null) { - return new async.Future.value(new HttpResponse.copy(cachedValue)); + var cachedResponse = (cache != null && method == 'GET') + ? cache.get(url) + : null; + if (cachedResponse != null) { + return new async.Future.value(new HttpResponse.copy(cachedResponse)); } var result = _backend.request(url, @@ -715,19 +699,14 @@ class Http { // TODO: Uncomment after apps migrate off of this class. // assert(value.status >= 200 && value.status < 300); - var response = new HttpResponse( - value.status, value.responseText, parseHeaders(value), - config); + var response = new HttpResponse(value.status, value.responseText, + parseHeaders(value), config); - if (cache != null) { - cache.put(url, response); - } + if (cache != null) cache.put(url, response); _pendingRequests.remove(url); return response; }, onError: (error) { - if (error is! dom.ProgressEvent) { - throw error; - } + if (error is! dom.ProgressEvent) throw error; dom.ProgressEvent event = error; _pendingRequests.remove(url); dom.HttpRequest request = event.currentTarget; @@ -735,8 +714,7 @@ class Http { new HttpResponse(request.status, request.response, parseHeaders(request), config)); }); - _pendingRequests[url] = result; - return result; + return _pendingRequests[url] = result; } _buildUrl(String url, Map params) { @@ -749,21 +727,18 @@ class Http { if (value is! List) value = [value]; value.forEach((v) { - if (v is Map) { - v = JSON.encode(v); - } - parts.add(_encodeUriQuery(key) + '=' + - _encodeUriQuery("$v")); + if (v is Map) v = JSON.encode(v); + parts.add(_encodeUriQuery(key) + '=' + _encodeUriQuery("$v")); }); }); return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); } _encodeUriQuery(val, {bool pctEncodeSpaces: false}) => - Uri.encodeComponent(val) - .replaceAll('%40', '@') - .replaceAll('%3A', ':') - .replaceAll('%24', r'$') - .replaceAll('%2C', ',') - .replaceAll('%20', pctEncodeSpaces ? '%20' : '+'); + Uri.encodeComponent(val) + .replaceAll('%40', '@') + .replaceAll('%3A', ':') + .replaceAll('%24', r'$') + .replaceAll('%2C', ',') + .replaceAll('%20', pctEncodeSpaces ? '%20' : '+'); } diff --git a/lib/mock/http_backend.dart b/lib/mock/http_backend.dart index b7a5623c0..a6f19bc0d 100644 --- a/lib/mock/http_backend.dart +++ b/lib/mock/http_backend.dart @@ -3,7 +3,7 @@ part of angular.mock; class _MockXhr { var $$method, $$url, $$async, $$reqHeaders, $$respHeaders; - open(method, url, async) { + void open(method, url, async) { $$method = method; $$url = url; $$async = async; @@ -13,24 +13,21 @@ class _MockXhr { var $$data; - send(data) { + void send(data) { $$data = data; } - setRequestHeader(key, value) { + void setRequestHeader(key, value) { $$reqHeaders[key] = value; } - getResponseHeader(name) { - // the lookup must be case insensitive, that's why we try two quick lookups and full scan at last - if ($$respHeaders.containsKey(name)) { - return $$respHeaders[name]; - } + String getResponseHeader(name) { + // the lookup must be case insensitive, that's why we try two quick + // lookups and full scan at last + if ($$respHeaders.containsKey(name)) return $$respHeaders[name]; name = name.toLowerCase(); - if ($$respHeaders.containsKey(name)) { - return $$respHeaders[name]; - } + if ($$respHeaders.containsKey(name)) return $$respHeaders[name]; String header = null; $$respHeaders.forEach((headerName, headerVal) { @@ -59,53 +56,51 @@ class _MockXhr { * An internal class used by [MockHttpBackend]. */ class MockHttpExpectation { - - var method, url, data, headers; + final method; + final url; + final data; + final headers; var response; MockHttpExpectation(this.method, this.url, [this.data, this.headers]); - match(m, u, [d, h]) { - if (method != m) return false; - if (!matchUrl(u)) return false; - if (d != null && !matchData(d)) return false; - if (h != null && !matchHeaders(h)) return false; + bool match(method, url, [data, headers]) { + if (method != method) return false; + if (!matchUrl(url)) return false; + if (data != null && !matchData(data)) return false; + if (headers != null && !matchHeaders(headers)) return false; return true; } - matchUrl(u) { + bool matchUrl(u) { if (url == null) return true; if (url is RegExp) return url.hasMatch(u); return url == u; } - matchHeaders(h) { + bool matchHeaders(h) { if (headers == null) return true; if (headers is Function) return headers(h); return "$headers" == "$h"; } - matchData(d) { + bool matchData(d) { if (data == null) return true; - if (d == null) return false; // data is not null, but d is. + if (d == null) return false; if (data is File) return data == d; assert(d is String); if (data is RegExp) return data.hasMatch(d); return JSON.encode(data) == JSON.encode(d); } - toString() { - return "$method $url"; - } + String toString() => "$method $url"; } class _Chain { - var _respondFn; - _Chain({respond}) { - _respondFn = respond; - } + final _respondFn; + _Chain({respond}): _respondFn = respond; respond([x,y,z]) => _respondFn(x,y,z); } @@ -129,12 +124,12 @@ class MockHttpBackend implements HttpBackend { if (status >= 200 && status < 300) { c.complete(new MockHttpRequest(status, data, headers)); } else { - c.completeError( - new MockProgressEvent( - new MockHttpRequest(status, data, headers))); + c.completeError(new MockProgressEvent( + new MockHttpRequest(status, data, headers))); } }; - call(method == null ? 'GET' : method, url, sendData, callback, requestHeaders); + call(method == null ? 'GET' : method, url, sendData, callback, + requestHeaders); return c.future; } @@ -150,9 +145,7 @@ class MockHttpBackend implements HttpBackend { data = statusOrDataOrFunction; headers = dataOrHeaders; } - if (data is Map || data is List) { - data = JSON.encode(data); - } + if (data is Map || data is List) data = JSON.encode(data); return ([a,b,c,d,e]) => [status, data, headers]; } @@ -162,7 +155,7 @@ class MockHttpBackend implements HttpBackend { * A callback oriented API. This function takes a callback with * will be called with (status, data, headers) */ - call(method, [url, data, callback, headers, timeout]) { + void call(method, [url, data, callback, headers, timeout]) { var xhr = new _MockXhr(), expectation = expectations.isEmpty ? null : expectations[0], wasExpected = false; @@ -177,11 +170,12 @@ class MockHttpBackend implements HttpBackend { var handleResponse = () { var response = wrapped.response(method, url, data, headers); xhr.$$respHeaders = response[2]; - utils.relaxFnApply(callback, [response[0], response[1], xhr.getAllResponseHeaders()]); + utils.relaxFnApply(callback, [response[0], response[1], + xhr.getAllResponseHeaders()]); }; var handleTimeout = () { - for (var i = 0, ii = responses.length; i < ii; i++) { + for (var i = 0; i < responses.length; i++) { if (identical(responses[i], handleResponse)) { responses.removeAt(i); callback(-1, null, ''); @@ -200,8 +194,9 @@ class MockHttpBackend implements HttpBackend { 'EXPECTED: ${prettyPrint(expectation.data)}\nGOT: $data']; if (!expectation.matchHeaders(headers)) - throw ['Expected $expectation with different headers\n' + - 'EXPECTED: ${prettyPrint(expectation.headers)}\nGOT: ${prettyPrint(headers)}']; + throw ['Expected $expectation with different headers\n' + 'EXPECTED: ${prettyPrint(expectation.headers)}\n' + 'GOT: ${prettyPrint(headers)}']; expectations.removeAt(0); @@ -223,8 +218,9 @@ class MockHttpBackend implements HttpBackend { } throw wasExpected ? ['No response defined !'] : - ['Unexpected request: $method $url\n' + - (expectation != null ? 'Expected $expectation' : 'No more requests expected')]; + ['Unexpected request: $method $url\n' + (expectation != null ? + 'Expected $expectation' : + 'No more requests expected')]; } /** @@ -233,21 +229,22 @@ class MockHttpBackend implements HttpBackend { * @param {string} method HTTP method. * @param {string|RegExp} url HTTP url. * @param {(string|RegExp)=} data HTTP request body. - * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header - * object and returns true if the headers match the current definition. - * @returns {requestHandler} Returns an object with `respond` method that control how a matched - * request is handled. + * @param {(Object|function(Object))=} headers HTTP headers or function that + * receives http header object and returns true if the headers match the + * current definition. + * @returns {requestHandler} Returns an object with `respond` method that + * control how a matched request is handled. * * - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}` * – The respond method takes a set of static data to be returned or a function that can return * an array containing response status (number), response data (string) and response headers * (Object). */ - when(method, [url, data, headers]) { + _Chain when(method, [url, data, headers]) { var definition = new MockHttpExpectation(method, url, data, headers), chain = new _Chain(respond: (status, data, headers) { - definition.response = _createResponse(status, data, headers); - }); + definition.response = _createResponse(status, data, headers); + }); definitions.add(definition); return chain; @@ -265,54 +262,41 @@ class MockHttpBackend implements HttpBackend { * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ - - - whenGET(url, [headers]) => - when('GET', url, null, headers); - whenDELETE(url, [headers]) => - when('DELETE', url, null, headers); - whenJSONP(url, [headers]) => - when('JSONP', url, null, headers); - - whenPUT(url, [data, headers]) => - when('PUT', url, data, headers); - whenPOST(url, [data, headers]) => - when('POST', url, data, headers); - whenPATCH(url, [data, headers]) => - when('PATCH', url, data, headers); + _Chain whenGET(url, [headers]) => when('GET', url, null, headers); /** * @ngdoc method - * @name ngMock.$httpBackend#whenHEAD + * @name ngMock.$httpBackend#whenDELETE * @methodOf ngMock.$httpBackend * @description - * Creates a new backend definition for HEAD requests. For more info see `when()`. + * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ + _Chain whenDELETE(url, [headers]) => when('DELETE', url, null, headers); /** * @ngdoc method - * @name ngMock.$httpBackend#whenDELETE + * @name ngMock.$httpBackend#whenJSONP * @methodOf ngMock.$httpBackend * @description - * Creates a new backend definition for DELETE requests. For more info see `when()`. + * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. - * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ + _Chain whenJSONP(url, [headers]) => when('JSONP', url, null, headers); /** * @ngdoc method - * @name ngMock.$httpBackend#whenPOST + * @name ngMock.$httpBackend#whenPUT * @methodOf ngMock.$httpBackend * @description - * Creates a new backend definition for POST requests. For more info see `when()`. + * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp)=} data HTTP request body. @@ -320,13 +304,14 @@ class MockHttpBackend implements HttpBackend { * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ + _Chain whenPUT(url, [data, headers]) => when('PUT', url, data, headers); /** * @ngdoc method - * @name ngMock.$httpBackend#whenPUT + * @name ngMock.$httpBackend#whenPOST * @methodOf ngMock.$httpBackend * @description - * Creates a new backend definition for PUT requests. For more info see `when()`. + * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp)=} data HTTP request body. @@ -334,20 +319,22 @@ class MockHttpBackend implements HttpBackend { * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ + _Chain whenPOST(url, [data, headers]) => when('POST', url, data, headers); + + _Chain whenPATCH(url, [data, headers]) => when('PATCH', url, data, headers); /** * @ngdoc method - * @name ngMock.$httpBackend#whenJSONP + * @name ngMock.$httpBackend#whenHEAD * @methodOf ngMock.$httpBackend * @description - * Creates a new backend definition for JSONP requests. For more info see `when()`. + * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp} url HTTP url. + * @param {(Object|function(Object))=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ - //createShortMethods('when'); - /** * @ngdoc method @@ -369,12 +356,12 @@ class MockHttpBackend implements HttpBackend { * an array containing response status (number), response data (string) and response headers * (Object). */ - expect(method, [url, data, headers]) { + _Chain expect(method, [url, data, headers]) { var expectation = new MockHttpExpectation(method, url, data, headers); expectations.add(expectation); return new _Chain(respond: (status, data, headers) { - expectation.response = _createResponse(status, data, headers); - }); + expectation.response = _createResponse(status, data, headers); + }); } @@ -390,52 +377,41 @@ class MockHttpBackend implements HttpBackend { * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. See #expect for more info. */ - expectGET(url, [headers]) => - expect('GET', url, null, headers); - expectDELETE(url, [headers]) => - expect('DELETE', url, null, headers); - expectJSONP(url, [headers]) => - expect('JSONP', url, null, headers); - - expectPUT(url, [data, headers]) => - expect('PUT', url, data, headers); - expectPOST(url, [data, headers]) => - expect('POST', url, data, headers); - expectPATCH(url, [data, headers]) => - expect('PATCH', url, data, headers); + _Chain expectGET(url, [headers]) => expect('GET', url, null, headers); /** * @ngdoc method - * @name ngMock.$httpBackend#expectHEAD + * @name ngMock.$httpBackend#expectDELETE * @methodOf ngMock.$httpBackend * @description - * Creates a new request expectation for HEAD requests. For more info see `expect()`. + * Creates a new request expectation for DELETE requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ + _Chain expectDELETE(url, [headers]) => expect('DELETE', url, null, headers); /** * @ngdoc method - * @name ngMock.$httpBackend#expectDELETE + * @name ngMock.$httpBackend#expectJSONP * @methodOf ngMock.$httpBackend * @description - * Creates a new request expectation for DELETE requests. For more info see `expect()`. + * Creates a new request expectation for JSONP requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. - * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ + _Chain expectJSONP(url, [headers]) => expect('JSONP', url, null, headers); /** * @ngdoc method - * @name ngMock.$httpBackend#expectPOST + * @name ngMock.$httpBackend#expectPUT * @methodOf ngMock.$httpBackend * @description - * Creates a new request expectation for POST requests. For more info see `expect()`. + * Creates a new request expectation for PUT requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp)=} data HTTP request body. @@ -443,13 +419,14 @@ class MockHttpBackend implements HttpBackend { * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ + _Chain expectPUT(url, [data, headers]) => expect('PUT', url, data, headers); /** * @ngdoc method - * @name ngMock.$httpBackend#expectPUT + * @name ngMock.$httpBackend#expectPOST * @methodOf ngMock.$httpBackend * @description - * Creates a new request expectation for PUT requests. For more info see `expect()`. + * Creates a new request expectation for POST requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. * @param {(string|RegExp)=} data HTTP request body. @@ -457,6 +434,7 @@ class MockHttpBackend implements HttpBackend { * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ + _Chain expectPOST(url, [data, headers]) => expect('POST', url, data, headers); /** * @ngdoc method @@ -471,20 +449,20 @@ class MockHttpBackend implements HttpBackend { * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ + _Chain expectPATCH(url, [data, headers]) => expect('PATCH', url, data, headers); /** * @ngdoc method - * @name ngMock.$httpBackend#expectJSONP + * @name ngMock.$httpBackend#expectHEAD * @methodOf ngMock.$httpBackend * @description - * Creates a new request expectation for JSONP requests. For more info see `expect()`. + * Creates a new request expectation for HEAD requests. For more info see `expect()`. * * @param {string|RegExp} url HTTP url. + * @param {Object=} headers HTTP headers. * @returns {requestHandler} Returns an object with `respond` method that control how a matched * request is handled. */ - //createShortMethods('expect'); - /** * @ngdoc method @@ -497,7 +475,7 @@ class MockHttpBackend implements HttpBackend { * all pending requests will be flushed. If there are no pending requests when the flush method * is called an exception is thrown (as this typically a sign of programming error). */ - flush([count]) { + void flush([count]) { if (responses.isEmpty) throw ['No pending request to flush !']; if (count != null) { @@ -529,7 +507,7 @@ class MockHttpBackend implements HttpBackend { * afterEach($httpBackend.verifyNoOutstandingExpectation); * */ - verifyNoOutstandingExpectation() { + void verifyNoOutstandingExpectation() { if (!expectations.isEmpty) { throw ['Unsatisfied requests: ${expectations.join(', ')}']; } @@ -550,10 +528,8 @@ class MockHttpBackend implements HttpBackend { * afterEach($httpBackend.verifyNoOutstandingRequest); * */ - verifyNoOutstandingRequest() { - if (!responses.isEmpty) { - throw ['Unflushed requests: ${responses.length}']; - } + void verifyNoOutstandingRequest() { + if (!responses.isEmpty) throw ['Unflushed requests: ${responses.length}']; } @@ -566,7 +542,7 @@ class MockHttpBackend implements HttpBackend { * call resetExpectations during a multiple-phase test when you want to reuse the same instance of * $httpBackend mock. */ - resetExpectations() { + void resetExpectations() { expectations.length = 0; responses.length = 0; } @@ -611,10 +587,7 @@ class MockHttpRequest implements HttpRequest { void abort() {} bool dispatchEvent(Event event) => false; - String getAllResponseHeaders() { - if (headers == null) return null; - return headers; - } + String getAllResponseHeaders() => headers; String getResponseHeader(String header) => null; void open(String method, String url, {bool async, String user, String password}) {} From 7025b16044620d7c7b04bdac16a05a27d4d44cfa Mon Sep 17 00:00:00 2001 From: Victor Date: Fri, 7 Feb 2014 16:34:37 +0100 Subject: [PATCH 2/2] refactor(http): remove a now useless workaround dartbug.com/13051 has been fixed. see https://code.google.com/p/dart/issues/detail?id=13051 for details. --- lib/core_dom/http.dart | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/lib/core_dom/http.dart b/lib/core_dom/http.dart index abcd91c6c..15f44dbc8 100644 --- a/lib/core_dom/http.dart +++ b/lib/core_dom/http.dart @@ -22,21 +22,11 @@ class HttpBackend { async.Future request(String url, {String method, bool withCredentials, String responseType, String mimeType, Map requestHeaders, sendData, - void onProgress(dom.ProgressEvent e)}) { - // Complete inside a then to work-around dartbug.com/13051 - var c = new async.Completer(); - - dom.HttpRequest.request(url, - method: method, - withCredentials: withCredentials, - responseType: responseType, - mimeType: mimeType, - requestHeaders: requestHeaders, - sendData: sendData, - onProgress: onProgress).then((x) => c.complete(x), - onError: (e, stackTrace) => c.completeError(e, stackTrace)); - return c.future; - } + void onProgress(dom.ProgressEvent e)}) => + dom.HttpRequest.request(url, method: method, + withCredentials: withCredentials, responseType: responseType, + mimeType: mimeType, requestHeaders: requestHeaders, + sendData: sendData, onProgress: onProgress); } @NgInjectableService()