Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 /** | 5 /** |
| 6 * @fileoverview | 6 * @fileoverview |
| 7 * Simple utilities for making XHRs more pleasant. | 7 * Simple utilities for making XHRs more pleasant. |
| 8 */ | 8 */ |
| 9 | 9 |
| 10 'use strict'; | 10 'use strict'; |
| 11 | 11 |
| 12 /** @suppress {duplicate} */ | 12 /** @suppress {duplicate} */ |
| 13 var remoting = remoting || {}; | 13 var remoting = remoting || {}; |
| 14 | 14 |
| 15 /** Namespace for XHR functions */ | 15 /** |
| 16 /** @type {Object} */ | 16 * Executes an arbitrary HTTP method asynchronously. |
| 17 remoting.xhr = remoting.xhr || {}; | 17 * |
| 18 * @constructor | |
| 19 * @param {remoting.Xhr.Params} params | |
| 20 */ | |
| 21 remoting.Xhr = function(params) { | |
| 22 /** @private @const {!XMLHttpRequest} */ | |
| 23 this.nativeXhr_ = new XMLHttpRequest(); | |
| 24 this.nativeXhr_.onreadystatechange = this.onReadyStateChange_.bind(this); | |
| 25 this.nativeXhr_.withCredentials = params.withCredentials || false; | |
| 18 | 26 |
| 19 /** | 27 /** @private @const */ |
| 20 * Takes an associative array of parameters and urlencodes it. | 28 this.responseType_ = params.responseType || remoting.Xhr.ResponseType.TEXT; |
| 21 * | 29 |
| 22 * @param {Object<string,string>} paramHash The parameter key/value pairs. | 30 // Apply URL parameters. |
| 23 * @return {string} URLEncoded version of paramHash. | 31 var url = params.url; |
| 24 */ | 32 var parameterString = ''; |
| 25 remoting.xhr.urlencodeParamHash = function(paramHash) { | 33 if (typeof(params.urlParams) === 'string') { |
| 26 var paramArray = []; | 34 parameterString = params.urlParams; |
| 27 for (var key in paramHash) { | 35 } else if (typeof(params.urlParams) === 'object') { |
| 28 paramArray.push(encodeURIComponent(key) + | 36 parameterString = remoting.Xhr.urlencodeParamHash( |
| 29 '=' + encodeURIComponent(paramHash[key])); | 37 remoting.Xhr.removeNullFields_(params.urlParams)); |
| 30 } | 38 } |
| 31 if (paramArray.length > 0) { | 39 if (parameterString) { |
| 32 return paramArray.join('&'); | 40 base.debug.assert(url.indexOf('?') == -1); |
| 41 url += '?' + parameterString; | |
| 33 } | 42 } |
| 34 return ''; | 43 |
| 44 // Check that the content spec is consistent. | |
| 45 if ((Number(params.textContent !== undefined) + | |
| 46 Number(params.formContent !== undefined) + | |
| 47 Number(params.jsonContent !== undefined)) > 1) { | |
| 48 throw new Error( | |
| 49 'may only specify one of textContent, formContent, and jsonContent'); | |
| 50 } | |
| 51 | |
| 52 // Prepare the build modified headers. | |
| 53 var headers = remoting.Xhr.removeNullFields_(params.headers); | |
| 54 | |
| 55 // Convert the content fields to a single text content variable. | |
| 56 /** @private {?string} */ | |
| 57 this.content_ = null; | |
| 58 if (params.textContent !== undefined) { | |
| 59 this.content_ = params.textContent; | |
| 60 } else if (params.formContent !== undefined) { | |
| 61 if (!('Content-type' in headers)) { | |
| 62 headers['Content-type'] = 'application/x-www-form-urlencoded'; | |
| 63 } | |
| 64 this.content_ = remoting.Xhr.urlencodeParamHash(params.formContent); | |
| 65 } else if (params.jsonContent !== undefined) { | |
| 66 if (!('Content-type' in headers)) { | |
| 67 headers['Content-type'] = 'application/json; charset=UTF-8'; | |
| 68 } | |
| 69 this.content_ = JSON.stringify(params.jsonContent); | |
| 70 } | |
| 71 | |
| 72 // Apply the oauthToken field. | |
| 73 if (params.oauthToken !== undefined) { | |
| 74 base.debug.assert(!('Authorization' in headers)); | |
| 75 headers['Authorization'] = 'Bearer ' + params.oauthToken; | |
| 76 } | |
| 77 | |
| 78 this.nativeXhr_.open(params.method, url, true); | |
| 79 for (var key in headers) { | |
| 80 this.nativeXhr_.setRequestHeader(key, headers[key]); | |
| 81 } | |
| 82 | |
| 83 /** @private {base.Deferred<!remoting.Xhr.Response>} */ | |
| 84 this.deferred_ = null; | |
| 35 }; | 85 }; |
| 36 | 86 |
| 37 /** | 87 /** |
| 88 * @enum {string} | |
| 89 */ | |
| 90 remoting.Xhr.ResponseType = { | |
| 91 /** Request a plain text response. */ | |
| 92 TEXT: 'TEXT', | |
| 93 /** Request a JSON response. */ | |
| 94 JSON: 'JSON', | |
| 95 /** Ignore any response body sent by the remote host. */ | |
| 96 NONE: 'NONE' | |
| 97 }; | |
| 98 | |
| 99 /** | |
| 38 * Parameters for the 'start' function. | 100 * Parameters for the 'start' function. |
| 39 * | 101 * |
| 40 * method: The HTTP method to use. | 102 * method: The HTTP method to use. |
| 41 * | 103 * |
| 42 * url: The URL to request. | 104 * url: The URL to request. |
| 43 * | 105 * |
| 44 * onDone: Function to call when the XHR finishes. | |
| 45 | |
| 46 * urlParams: (optional) Parameters to be appended to the URL. | 106 * urlParams: (optional) Parameters to be appended to the URL. |
| 47 * Null-valued parameters are omitted. | 107 * Null-valued parameters are omitted. |
| 48 * | 108 * |
| 49 * textContent: (optional) Text to be sent as the request body. | 109 * textContent: (optional) Text to be sent as the request body. |
| 50 * | 110 * |
| 51 * formContent: (optional) Data to be URL-encoded and sent as the | 111 * formContent: (optional) Data to be URL-encoded and sent as the |
| 52 * request body. Causes Content-type header to be set | 112 * request body. Causes Content-type header to be set |
| 53 * appropriately. | 113 * appropriately. |
| 54 * | 114 * |
| 55 * jsonContent: (optional) Data to be JSON-encoded and sent as the | 115 * jsonContent: (optional) Data to be JSON-encoded and sent as the |
| 56 * request body. Causes Content-type header to be set | 116 * request body. Causes Content-type header to be set |
| 57 * appropriately. | 117 * appropriately. |
| 58 * | 118 * |
| 59 * headers: (optional) Additional request headers to be sent. | 119 * headers: (optional) Additional request headers to be sent. |
| 60 * Null-valued headers are omitted. | 120 * Null-valued headers are omitted. |
| 61 * | 121 * |
| 62 * withCredentials: (optional) Value of the XHR's withCredentials field. | 122 * withCredentials: (optional) Value of the XHR's withCredentials field. |
| 63 * | 123 * |
| 124 * useOauth: (optional) If true, use OAuth2 to authenticate the request. | |
| 125 * Not compatible with the oauthToken field. | |
| 126 * | |
| 64 * oauthToken: (optional) An OAuth2 token used to construct an | 127 * oauthToken: (optional) An OAuth2 token used to construct an |
| 65 * Authentication header. | 128 * Authentication header. Not compatible with the useOauth field. |
| 129 * | |
| 130 * responseType: (optional) Request a response of a specific | |
| 131 * type. Default: TEXT. | |
| 66 * | 132 * |
| 67 * @typedef {{ | 133 * @typedef {{ |
| 68 * method: string, | 134 * method: string, |
| 69 * url:string, | 135 * url:string, |
| 70 * onDone:(function(XMLHttpRequest):void), | |
| 71 * urlParams:(string|Object<string,?string>|undefined), | 136 * urlParams:(string|Object<string,?string>|undefined), |
| 72 * textContent:(string|undefined), | 137 * textContent:(string|undefined), |
| 73 * formContent:(Object|undefined), | 138 * formContent:(Object|undefined), |
| 74 * jsonContent:(*|undefined), | 139 * jsonContent:(*|undefined), |
| 75 * headers:(Object<string,?string>|undefined), | 140 * headers:(Object<string,?string>|undefined), |
| 76 * withCredentials:(boolean|undefined), | 141 * withCredentials:(boolean|undefined), |
| 77 * oauthToken:(string|undefined) | 142 * useOauth:(boolean|undefined), |
| 143 * oauthToken:(string|undefined), | |
| 144 * responseType:(remoting.Xhr.ResponseType|undefined) | |
| 78 * }} | 145 * }} |
| 79 */ | 146 */ |
| 80 remoting.XhrParams; | 147 remoting.Xhr.Params; |
| 148 | |
| 149 /** | |
| 150 * Aborts the HTTP request. Does nothing is the request has finished | |
| 151 * already. | |
| 152 */ | |
| 153 remoting.Xhr.prototype.abort = function() { | |
| 154 return this.nativeXhr_.abort(); | |
| 155 }; | |
| 156 | |
| 157 /** | |
| 158 * Gets a promise that is resolved when the request completes. | |
| 159 * | |
| 160 * If an HTTP status code outside the 200..299 range is returned, the | |
| 161 * promise is rejected with a remoting.Error by default. Setting | |
| 162 * resolveOnErrorStatus to true in the constructor parameters allows | |
| 163 * the promise to resolve for any HTTP status code. | |
| 164 * | |
| 165 * Any error that prevents the HTTP request from succeeding causes | |
| 166 * this promise to be rejected. | |
| 167 * | |
| 168 * NOTE: Calling this method more than once will return the same | |
| 169 * promise and not start a new request, despite what the name | |
| 170 * suggests. | |
| 171 * | |
| 172 * @return {!Promise<!remoting.Xhr.Response>} | |
| 173 */ | |
| 174 remoting.Xhr.prototype.start = function() { | |
| 175 if (this.deferred_ == null) { | |
| 176 var xhr = this.nativeXhr_; | |
| 177 xhr.send(this.content_); | |
| 178 this.content_ = null; // for gc | |
| 179 this.deferred_ = new base.Deferred(); | |
| 180 } | |
| 181 return this.deferred_.promise(); | |
| 182 }; | |
| 183 | |
| 184 /** | |
| 185 * @private | |
| 186 */ | |
| 187 remoting.Xhr.prototype.onReadyStateChange_ = function() { | |
|
kelvinp
2015/03/17 22:06:20
Probably worth adding a comment saying that if you
John Williams
2015/03/18 20:07:23
Done.
| |
| 188 var xhr = this.nativeXhr_; | |
| 189 if (xhr.readyState == 4) { | |
| 190 this.deferred_.resolve(new remoting.Xhr.Response(xhr, this.responseType_)); | |
| 191 } | |
| 192 }; | |
| 193 | |
| 194 /** | |
| 195 * @constructor | |
| 196 * @param {!XMLHttpRequest} xhr | |
| 197 * @param {remoting.Xhr.ResponseType} type | |
| 198 */ | |
| 199 remoting.Xhr.Response = function(xhr, type) { | |
| 200 /** @private @const */ | |
| 201 this.type_ = type; | |
| 202 | |
| 203 /** | |
| 204 * The HTTP status code. | |
| 205 * @const {number} | |
| 206 */ | |
| 207 this.status = xhr.status; | |
| 208 | |
| 209 /** | |
| 210 * The HTTP status description. | |
| 211 * @const {string} | |
| 212 */ | |
| 213 this.statusText = xhr.statusText; | |
| 214 | |
| 215 /** | |
| 216 * The response URL, if any. | |
| 217 * @const {?string} | |
| 218 */ | |
| 219 this.url = xhr.responseURL; | |
| 220 | |
| 221 /** @private {string} */ | |
| 222 this.text_ = xhr.responseText || ''; | |
| 223 }; | |
| 224 | |
| 225 /** | |
| 226 * @return {string} The text content of the response. | |
| 227 */ | |
| 228 remoting.Xhr.Response.prototype.getText = function() { | |
| 229 return this.text_; | |
| 230 }; | |
| 231 | |
| 232 /** | |
| 233 * @return {*} The parsed JSON content of the response. | |
| 234 */ | |
| 235 remoting.Xhr.Response.prototype.getJson = function() { | |
| 236 base.debug.assert(this.type_ == remoting.Xhr.ResponseType.JSON); | |
| 237 return JSON.parse(this.text_); | |
|
kelvinp
2015/03/17 22:06:20
This may throw, should we wrap in try catch and re
John Williams
2015/03/18 20:07:23
IMHO returning null in the case of an error is an
| |
| 238 }; | |
| 81 | 239 |
| 82 /** | 240 /** |
| 83 * Returns a copy of the input object with all null or undefined | 241 * Returns a copy of the input object with all null or undefined |
| 84 * fields removed. | 242 * fields removed. |
| 85 * | 243 * |
| 86 * @param {Object<string,?string>|undefined} input | 244 * @param {Object<string,?string>|undefined} input |
| 87 * @return {!Object<string,string>} | 245 * @return {!Object<string,string>} |
| 88 * @private | 246 * @private |
| 89 */ | 247 */ |
| 90 remoting.xhr.removeNullFields_ = function(input) { | 248 remoting.Xhr.removeNullFields_ = function(input) { |
| 91 /** @type {!Object<string,string>} */ | 249 /** @type {!Object<string,string>} */ |
| 92 var result = {}; | 250 var result = {}; |
| 93 if (input) { | 251 if (input) { |
| 94 for (var field in input) { | 252 for (var field in input) { |
| 95 var value = input[field]; | 253 var value = input[field]; |
| 96 if (value != null) { | 254 if (value != null) { |
| 97 result[field] = value; | 255 result[field] = value; |
| 98 } | 256 } |
| 99 } | 257 } |
| 100 } | 258 } |
| 101 return result; | 259 return result; |
| 102 }; | 260 }; |
| 103 | 261 |
| 104 /** | 262 /** |
| 105 * Executes an arbitrary HTTP method asynchronously. | 263 * Takes an associative array of parameters and urlencodes it. |
| 106 * | 264 * |
| 107 * @param {remoting.XhrParams} params | 265 * @param {Object<string,string>} paramHash The parameter key/value pairs. |
| 108 * @return {XMLHttpRequest} The XMLHttpRequest object. | 266 * @return {string} URLEncoded version of paramHash. |
| 109 */ | 267 */ |
| 110 remoting.xhr.start = function(params) { | 268 remoting.Xhr.urlencodeParamHash = function(paramHash) { |
| 111 // Extract fields that can be used more or less as-is. | 269 var paramArray = []; |
| 112 var method = params.method; | 270 for (var key in paramHash) { |
| 113 var url = params.url; | 271 paramArray.push(encodeURIComponent(key) + |
| 114 var onDone = params.onDone; | 272 '=' + encodeURIComponent(paramHash[key])); |
| 115 var headers = remoting.xhr.removeNullFields_(params.headers); | |
| 116 var withCredentials = params.withCredentials || false; | |
| 117 | |
| 118 // Apply URL parameters. | |
| 119 var parameterString = ''; | |
| 120 if (typeof(params.urlParams) === 'string') { | |
| 121 parameterString = params.urlParams; | |
| 122 } else if (typeof(params.urlParams) === 'object') { | |
| 123 parameterString = remoting.xhr.urlencodeParamHash( | |
| 124 remoting.xhr.removeNullFields_(params.urlParams)); | |
| 125 } | 273 } |
| 126 if (parameterString) { | 274 if (paramArray.length > 0) { |
| 127 base.debug.assert(url.indexOf('?') == -1); | 275 return paramArray.join('&'); |
| 128 url += '?' + parameterString; | |
| 129 } | 276 } |
| 130 | 277 return ''; |
| 131 // Check that the content spec is consistent. | |
| 132 if ((Number(params.textContent !== undefined) + | |
| 133 Number(params.formContent !== undefined) + | |
| 134 Number(params.jsonContent !== undefined)) > 1) { | |
| 135 throw new Error( | |
| 136 'may only specify one of textContent, formContent, and jsonContent'); | |
| 137 } | |
| 138 | |
| 139 // Convert the content fields to a single text content variable. | |
| 140 /** @type {?string} */ | |
| 141 var content = null; | |
| 142 if (params.textContent !== undefined) { | |
| 143 content = params.textContent; | |
| 144 } else if (params.formContent !== undefined) { | |
| 145 if (!('Content-type' in headers)) { | |
| 146 headers['Content-type'] = 'application/x-www-form-urlencoded'; | |
| 147 } | |
| 148 content = remoting.xhr.urlencodeParamHash(params.formContent); | |
| 149 } else if (params.jsonContent !== undefined) { | |
| 150 if (!('Content-type' in headers)) { | |
| 151 headers['Content-type'] = 'application/json; charset=UTF-8'; | |
| 152 } | |
| 153 content = JSON.stringify(params.jsonContent); | |
| 154 } | |
| 155 | |
| 156 // Apply the oauthToken field. | |
| 157 if (params.oauthToken !== undefined) { | |
| 158 base.debug.assert(!('Authorization' in headers)); | |
| 159 headers['Authorization'] = 'Bearer ' + params.oauthToken; | |
| 160 } | |
| 161 | |
| 162 return remoting.xhr.startInternal_( | |
| 163 method, url, onDone, content, headers, withCredentials); | |
| 164 }; | |
| 165 | |
| 166 /** | |
| 167 * Executes an arbitrary HTTP method asynchronously. | |
| 168 * | |
| 169 * @param {string} method | |
| 170 * @param {string} url | |
| 171 * @param {function(XMLHttpRequest):void} onDone | |
| 172 * @param {?string} content | |
| 173 * @param {!Object<string,string>} headers | |
| 174 * @param {boolean} withCredentials | |
| 175 * @return {XMLHttpRequest} The XMLHttpRequest object. | |
| 176 * @private | |
| 177 */ | |
| 178 remoting.xhr.startInternal_ = function( | |
| 179 method, url, onDone, content, headers, withCredentials) { | |
| 180 /** @type {XMLHttpRequest} */ | |
| 181 var xhr = new XMLHttpRequest(); | |
| 182 xhr.onreadystatechange = function() { | |
| 183 if (xhr.readyState != 4) { | |
| 184 return; | |
| 185 } | |
| 186 onDone(xhr); | |
| 187 }; | |
| 188 | |
| 189 xhr.open(method, url, true); | |
| 190 for (var key in headers) { | |
| 191 xhr.setRequestHeader(key, headers[key]); | |
| 192 } | |
| 193 xhr.withCredentials = withCredentials; | |
| 194 xhr.send(content); | |
| 195 return xhr; | |
| 196 }; | 278 }; |
| 197 | 279 |
| 198 /** | 280 /** |
| 199 * Generic success/failure response proxy. | 281 * Generic success/failure response proxy. |
| 282 * TODO(jrw): Stop using this. | |
| 200 * | 283 * |
| 201 * @param {function():void} onDone | 284 * @param {function():void} onDone |
| 202 * @param {function(!remoting.Error):void} onError | 285 * @param {function(!remoting.Error):void} onError |
| 203 * @param {Array<remoting.Error.Tag>=} opt_ignoreErrors | 286 * @param {Array<remoting.Error.Tag>=} opt_ignoreErrors |
| 204 * @return {function(XMLHttpRequest):void} | 287 * @return {function(!remoting.Xhr.Response):void} |
| 205 */ | 288 */ |
| 206 remoting.xhr.defaultResponse = function(onDone, onError, opt_ignoreErrors) { | 289 remoting.Xhr.defaultResponse = function(onDone, onError, opt_ignoreErrors) { |
| 207 /** @param {XMLHttpRequest} xhr */ | 290 /** @param {!remoting.Xhr.Response} response */ |
| 208 var result = function(xhr) { | 291 var result = function(response) { |
| 209 var error = | 292 var error = remoting.Error.fromHttpStatus(response.status); |
| 210 remoting.Error.fromHttpStatus(/** @type {number} */ (xhr.status)); | 293 if (error.isNone()) { |
| 211 if (!error.isError()) { | |
| 212 onDone(); | 294 onDone(); |
| 213 return; | 295 return; |
| 214 } | 296 } |
| 215 | 297 |
| 216 if (opt_ignoreErrors && opt_ignoreErrors.indexOf(error.tag) !== -1) { | 298 if (opt_ignoreErrors && error.hasTag.apply(error, opt_ignoreErrors)) { |
| 217 onDone(); | 299 onDone(); |
| 218 return; | 300 return; |
| 219 } | 301 } |
| 220 | 302 |
| 221 onError(error); | 303 onError(error); |
| 222 }; | 304 }; |
| 223 return result; | 305 return result; |
| 224 }; | 306 }; |
| OLD | NEW |