| 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 * Utility class for making XHRs more pleasant. | 7 * Utility class 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 /** | 15 /** |
| 16 * @constructor | 16 * @constructor |
| 17 * @param {remoting.Xhr.Params} params | 17 * @param {remoting.Xhr.Params} params |
| 18 */ | 18 */ |
| 19 remoting.Xhr = function(params) { | 19 remoting.Xhr = function(params) { |
| 20 /** @private @const {!XMLHttpRequest} */ | 20 remoting.Xhr.checkParams_(params); |
| 21 this.nativeXhr_ = new XMLHttpRequest(); | |
| 22 this.nativeXhr_.onreadystatechange = this.onReadyStateChange_.bind(this); | |
| 23 this.nativeXhr_.withCredentials = params.withCredentials || false; | |
| 24 | |
| 25 /** @private @const */ | |
| 26 this.responseType_ = params.responseType || remoting.Xhr.ResponseType.TEXT; | |
| 27 | 21 |
| 28 // Apply URL parameters. | 22 // Apply URL parameters. |
| 29 var url = params.url; | 23 var url = params.url; |
| 30 var parameterString = ''; | 24 var parameterString = ''; |
| 31 if (typeof(params.urlParams) === 'string') { | 25 if (typeof(params.urlParams) === 'string') { |
| 32 parameterString = params.urlParams; | 26 parameterString = params.urlParams; |
| 33 } else if (typeof(params.urlParams) === 'object') { | 27 } else if (typeof(params.urlParams) === 'object') { |
| 34 parameterString = remoting.Xhr.urlencodeParamHash( | 28 parameterString = remoting.Xhr.urlencodeParamHash( |
| 35 remoting.Xhr.removeNullFields_(params.urlParams)); | 29 remoting.Xhr.removeNullFields_(params.urlParams)); |
| 36 } | 30 } |
| 37 if (parameterString) { | 31 if (parameterString) { |
| 38 base.debug.assert(url.indexOf('?') == -1); | |
| 39 url += '?' + parameterString; | 32 url += '?' + parameterString; |
| 40 } | 33 } |
| 41 | 34 |
| 42 // Check that the content spec is consistent. | |
| 43 if ((Number(params.textContent !== undefined) + | |
| 44 Number(params.formContent !== undefined) + | |
| 45 Number(params.jsonContent !== undefined)) > 1) { | |
| 46 throw new Error( | |
| 47 'may only specify one of textContent, formContent, and jsonContent'); | |
| 48 } | |
| 49 | |
| 50 // Prepare the build modified headers. | 35 // Prepare the build modified headers. |
| 51 var headers = remoting.Xhr.removeNullFields_(params.headers); | 36 /** @const */ |
| 37 this.headers_ = remoting.Xhr.removeNullFields_(params.headers); |
| 52 | 38 |
| 53 // Convert the content fields to a single text content variable. | 39 // Convert the content fields to a single text content variable. |
| 54 /** @private {?string} */ | 40 /** @private {?string} */ |
| 55 this.content_ = null; | 41 this.content_ = null; |
| 56 if (params.textContent !== undefined) { | 42 if (params.textContent !== undefined) { |
| 43 this.maybeSetContentType_('text/plain'); |
| 57 this.content_ = params.textContent; | 44 this.content_ = params.textContent; |
| 58 } else if (params.formContent !== undefined) { | 45 } else if (params.formContent !== undefined) { |
| 59 if (!('Content-type' in headers)) { | 46 this.maybeSetContentType_('application/x-www-form-urlencoded'); |
| 60 headers['Content-type'] = 'application/x-www-form-urlencoded'; | |
| 61 } | |
| 62 this.content_ = remoting.Xhr.urlencodeParamHash(params.formContent); | 47 this.content_ = remoting.Xhr.urlencodeParamHash(params.formContent); |
| 63 } else if (params.jsonContent !== undefined) { | 48 } else if (params.jsonContent !== undefined) { |
| 64 if (!('Content-type' in headers)) { | 49 this.maybeSetContentType_('application/json'); |
| 65 headers['Content-type'] = 'application/json; charset=UTF-8'; | |
| 66 } | |
| 67 this.content_ = JSON.stringify(params.jsonContent); | 50 this.content_ = JSON.stringify(params.jsonContent); |
| 68 } | 51 } |
| 69 | 52 |
| 70 // Apply the oauthToken field. | 53 // Apply the oauthToken field. |
| 71 if (params.oauthToken !== undefined) { | 54 if (params.oauthToken !== undefined) { |
| 72 base.debug.assert(!('Authorization' in headers)); | 55 this.setAuthToken_(params.oauthToken); |
| 73 headers['Authorization'] = 'Bearer ' + params.oauthToken; | |
| 74 } | 56 } |
| 75 | 57 |
| 58 /** @private @const {boolean} */ |
| 59 this.acceptJson_ = params.acceptJson || false; |
| 60 if (this.acceptJson_) { |
| 61 this.maybeSetHeader_('Accept', 'application/json'); |
| 62 } |
| 63 |
| 64 // Apply useIdentity field. |
| 65 /** @const {boolean} */ |
| 66 this.useIdentity_ = params.useIdentity || false; |
| 67 |
| 68 /** @private @const {!XMLHttpRequest} */ |
| 69 this.nativeXhr_ = new XMLHttpRequest(); |
| 70 this.nativeXhr_.onreadystatechange = this.onReadyStateChange_.bind(this); |
| 71 this.nativeXhr_.withCredentials = params.withCredentials || false; |
| 76 this.nativeXhr_.open(params.method, url, true); | 72 this.nativeXhr_.open(params.method, url, true); |
| 77 for (var key in headers) { | |
| 78 this.nativeXhr_.setRequestHeader(key, headers[key]); | |
| 79 } | |
| 80 | 73 |
| 81 /** @private {base.Deferred<!remoting.Xhr.Response>} */ | 74 /** @private {base.Deferred<!remoting.Xhr.Response>} */ |
| 82 this.deferred_ = null; | 75 this.deferred_ = null; |
| 76 |
| 77 /** @private {boolean} True if the request has been aborted. */ |
| 78 this.aborted_ = false; |
| 83 }; | 79 }; |
| 84 | 80 |
| 85 /** | 81 /** |
| 86 * @enum {string} | 82 * Parameters for the 'start' function. Unless otherwise noted, all |
| 87 */ | 83 * parameters are optional. |
| 88 remoting.Xhr.ResponseType = { | |
| 89 TEXT: 'TEXT', // Request a plain text response (default). | |
| 90 JSON: 'JSON', // Request a JSON response. | |
| 91 NONE: 'NONE' // Don't request any response. | |
| 92 }; | |
| 93 | |
| 94 /** | |
| 95 * Parameters for the 'start' function. | |
| 96 * | 84 * |
| 97 * method: The HTTP method to use. | 85 * method: (required) The HTTP method to use. |
| 98 * | 86 * |
| 99 * url: The URL to request. | 87 * url: (required) The URL to request. |
| 100 * | 88 * |
| 101 * urlParams: (optional) Parameters to be appended to the URL. | 89 * urlParams: Parameters to be appended to the URL. Null-valued |
| 102 * Null-valued parameters are omitted. | 90 * parameters are omitted. |
| 103 * | 91 * |
| 104 * textContent: (optional) Text to be sent as the request body. | 92 * textContent: Text to be sent as the request body. |
| 105 * | 93 * |
| 106 * formContent: (optional) Data to be URL-encoded and sent as the | 94 * formContent: Data to be URL-encoded and sent as the request body. |
| 107 * request body. Causes Content-type header to be set | 95 * Causes Content-type header to be set appropriately. |
| 108 * appropriately. | |
| 109 * | 96 * |
| 110 * jsonContent: (optional) Data to be JSON-encoded and sent as the | 97 * jsonContent: Data to be JSON-encoded and sent as the request body. |
| 111 * request body. Causes Content-type header to be set | 98 * Causes Content-type header to be set appropriately. |
| 112 * appropriately. | |
| 113 * | 99 * |
| 114 * headers: (optional) Additional request headers to be sent. | 100 * headers: Additional request headers to be sent. Null-valued |
| 115 * Null-valued headers are omitted. | 101 * headers are omitted. |
| 116 * | 102 * |
| 117 * withCredentials: (optional) Value of the XHR's withCredentials field. | 103 * withCredentials: Value of the XHR's withCredentials field. |
| 118 * | 104 * |
| 119 * oauthToken: (optional) An OAuth2 token used to construct an | 105 * oauthToken: An OAuth2 token used to construct an Authentication |
| 120 * Authentication header. | 106 * header. |
| 121 * | 107 * |
| 122 * responseType: (optional) Request a response of a specific | 108 * useIdentity: Use identity API to get an OAuth2 token. |
| 123 * type. Default: TEXT. | 109 * |
| 110 * acceptJson: If true, send an Accept header indicating that a JSON |
| 111 * response is expected. |
| 124 * | 112 * |
| 125 * @typedef {{ | 113 * @typedef {{ |
| 126 * method: string, | 114 * method: string, |
| 127 * url:string, | 115 * url:string, |
| 128 * urlParams:(string|Object<string,?string>|undefined), | 116 * urlParams:(string|Object<string,?string>|undefined), |
| 129 * textContent:(string|undefined), | 117 * textContent:(string|undefined), |
| 130 * formContent:(Object|undefined), | 118 * formContent:(Object|undefined), |
| 131 * jsonContent:(*|undefined), | 119 * jsonContent:(*|undefined), |
| 132 * headers:(Object<string,?string>|undefined), | 120 * headers:(Object<string,?string>|undefined), |
| 133 * withCredentials:(boolean|undefined), | 121 * withCredentials:(boolean|undefined), |
| 134 * oauthToken:(string|undefined), | 122 * oauthToken:(string|undefined), |
| 135 * responseType:(remoting.Xhr.ResponseType|undefined) | 123 * useIdentity:(boolean|undefined), |
| 124 * acceptJson:(boolean|undefined) |
| 136 * }} | 125 * }} |
| 137 */ | 126 */ |
| 138 remoting.Xhr.Params; | 127 remoting.Xhr.Params; |
| 139 | 128 |
| 140 /** | 129 /** |
| 141 * Aborts the HTTP request. Does nothing is the request has finished | 130 * Aborts the HTTP request. Does nothing if the request has finished |
| 142 * already. | 131 * already. Prevents the promise returned by start() from ever being |
| 132 * resolved or rejected. |
| 143 */ | 133 */ |
| 144 remoting.Xhr.prototype.abort = function() { | 134 remoting.Xhr.prototype.abort = function() { |
| 145 this.nativeXhr_.abort(); | 135 this.aborted_ = true; |
| 136 try { |
| 137 this.nativeXhr_.abort(); |
| 138 } catch (error) { |
| 139 // This abort method throws an exception if called before the |
| 140 // request is sent. This isn't an error for our purposes, so we |
| 141 // just ignore the exception. |
| 142 } |
| 146 }; | 143 }; |
| 147 | 144 |
| 148 /** | 145 /** |
| 149 * Starts and HTTP request and gets a promise that is resolved when | 146 * Starts and HTTP request and gets a promise that is resolved when |
| 150 * the request completes. | 147 * the request completes. |
| 151 * | 148 * |
| 152 * Any error that prevents receiving an HTTP status | 149 * Any error that prevents sending the request causes the promise to |
| 153 * code causes this promise to be rejected. | 150 * be rejected. |
| 154 * | 151 * |
| 155 * NOTE: Calling this method more than once will return the same | 152 * NOTE: Calling this method more than once will return the same |
| 156 * promise and not start a new request, despite what the name | 153 * promise and not start a new request, despite what the name |
| 157 * suggests. | 154 * suggests. |
| 158 * | 155 * |
| 159 * @return {!Promise<!remoting.Xhr.Response>} | 156 * @return {!Promise<!remoting.Xhr.Response>} |
| 160 */ | 157 */ |
| 161 remoting.Xhr.prototype.start = function() { | 158 remoting.Xhr.prototype.start = function() { |
| 162 if (this.deferred_ == null) { | 159 if (this.deferred_ == null) { |
| 163 var xhr = this.nativeXhr_; | |
| 164 xhr.send(this.content_); | |
| 165 this.content_ = null; // for gc | |
| 166 this.deferred_ = new base.Deferred(); | 160 this.deferred_ = new base.Deferred(); |
| 161 |
| 162 // Send the XHR, possibly after getting an OAuth token. |
| 163 var that = this; |
| 164 if (this.useIdentity_) { |
| 165 remoting.identity.getToken().then(function(token) { |
| 166 base.debug.assert(that.nativeXhr_.readyState == 1); |
| 167 that.setAuthToken_(token); |
| 168 that.sendXhr_(); |
| 169 }).catch(function(error) { |
| 170 if (!that.aborted_) { |
| 171 that.deferred_.reject(error); |
| 172 } |
| 173 }); |
| 174 } else { |
| 175 this.sendXhr_(); |
| 176 } |
| 167 } | 177 } |
| 168 return this.deferred_.promise(); | 178 return this.deferred_.promise(); |
| 169 }; | 179 }; |
| 170 | 180 |
| 171 /** | 181 /** |
| 182 * @param {remoting.Xhr.Params} params |
| 183 * @throws {Error} if params are invalid |
| 184 */ |
| 185 remoting.Xhr.checkParams_ = function(params) { |
| 186 if (params.urlParams) { |
| 187 if (params.url.indexOf('?') != -1) { |
| 188 throw new Error('URL may not contain "?" when urlParams is set'); |
| 189 } |
| 190 if (params.url.indexOf('#') != -1) { |
| 191 throw new Error('URL may not contain "#" when urlParams is set'); |
| 192 } |
| 193 } |
| 194 |
| 195 if ((Number(params.textContent !== undefined) + |
| 196 Number(params.formContent !== undefined) + |
| 197 Number(params.jsonContent !== undefined)) > 1) { |
| 198 throw new Error( |
| 199 'may only specify one of textContent, formContent, and jsonContent'); |
| 200 } |
| 201 |
| 202 if (params.useIdentity && params.oauthToken !== undefined) { |
| 203 throw new Error('may not specify both useIdentity and oauthToken'); |
| 204 } |
| 205 |
| 206 if ((params.useIdentity || params.oauthToken !== undefined) && |
| 207 params.headers && |
| 208 params.headers['Authorization'] != null) { |
| 209 throw new Error( |
| 210 'may not specify useIdentity or oauthToken ' + |
| 211 'with an Authorization header'); |
| 212 } |
| 213 }; |
| 214 |
| 215 /** |
| 216 * @param {string} token |
| 217 * @private |
| 218 */ |
| 219 remoting.Xhr.prototype.setAuthToken_ = function(token) { |
| 220 this.setHeader_('Authorization', 'Bearer ' + token); |
| 221 }; |
| 222 |
| 223 /** |
| 224 * @param {string} type |
| 225 * @private |
| 226 */ |
| 227 remoting.Xhr.prototype.maybeSetContentType_ = function(type) { |
| 228 this.maybeSetHeader_('Content-type', type + '; charset=UTF-8'); |
| 229 }; |
| 230 |
| 231 /** |
| 232 * @param {string} key |
| 233 * @param {string} value |
| 234 * @private |
| 235 */ |
| 236 remoting.Xhr.prototype.setHeader_ = function(key, value) { |
| 237 var wasSet = this.maybeSetHeader_(key, value); |
| 238 base.debug.assert(wasSet); |
| 239 }; |
| 240 |
| 241 /** |
| 242 * @param {string} key |
| 243 * @param {string} value |
| 244 * @return {boolean} |
| 245 * @private |
| 246 */ |
| 247 remoting.Xhr.prototype.maybeSetHeader_ = function(key, value) { |
| 248 if (!(key in this.headers_)) { |
| 249 this.headers_[key] = value; |
| 250 return true; |
| 251 } |
| 252 return false; |
| 253 }; |
| 254 |
| 255 /** @private */ |
| 256 remoting.Xhr.prototype.sendXhr_ = function() { |
| 257 if (!this.aborted_) { |
| 258 for (var key in this.headers_) { |
| 259 this.nativeXhr_.setRequestHeader(key, this.headers_[key]); |
| 260 } |
| 261 this.nativeXhr_.send(this.content_); |
| 262 } |
| 263 this.content_ = null; // for gc |
| 264 }; |
| 265 |
| 266 /** |
| 172 * @private | 267 * @private |
| 173 */ | 268 */ |
| 174 remoting.Xhr.prototype.onReadyStateChange_ = function() { | 269 remoting.Xhr.prototype.onReadyStateChange_ = function() { |
| 175 var xhr = this.nativeXhr_; | 270 var xhr = this.nativeXhr_; |
| 176 if (xhr.readyState == 4) { | 271 if (xhr.readyState == 4 && !this.aborted_) { |
| 177 // See comments at remoting.Xhr.Response. | 272 // See comments at remoting.Xhr.Response. |
| 178 this.deferred_.resolve(new remoting.Xhr.Response(xhr, this.responseType_)); | 273 this.deferred_.resolve(new remoting.Xhr.Response( |
| 274 xhr, this.acceptJson_)); |
| 179 } | 275 } |
| 180 }; | 276 }; |
| 181 | 277 |
| 182 /** | 278 /** |
| 183 * The response-related parts of an XMLHttpRequest. Note that this | 279 * The response-related parts of an XMLHttpRequest. Note that this |
| 184 * class is not just a facade for XMLHttpRequest; it saves the value | 280 * class is not just a facade for XMLHttpRequest; it saves the value |
| 185 * of the |responseText| field becuase once onReadyStateChange_ | 281 * of the |responseText| field becuase once onReadyStateChange_ |
| 186 * (above) returns, the value of |responseText| is reset to the empty | 282 * (above) returns, the value of |responseText| is reset to the empty |
| 187 * string! This is a documented anti-feature of the XMLHttpRequest | 283 * string! This is a documented anti-feature of the XMLHttpRequest |
| 188 * API. | 284 * API. |
| 189 * | 285 * |
| 190 * @constructor | 286 * @constructor |
| 191 * @param {!XMLHttpRequest} xhr | 287 * @param {!XMLHttpRequest} xhr |
| 192 * @param {remoting.Xhr.ResponseType} type | 288 * @param {boolean} allowJson |
| 193 */ | 289 */ |
| 194 remoting.Xhr.Response = function(xhr, type) { | 290 remoting.Xhr.Response = function(xhr, allowJson) { |
| 195 /** @private @const */ | 291 /** @private @const */ |
| 196 this.type_ = type; | 292 this.allowJson_ = allowJson; |
| 197 | 293 |
| 198 /** | 294 /** |
| 199 * The HTTP status code. | 295 * The HTTP status code. |
| 200 * @const {number} | 296 * @const {number} |
| 201 */ | 297 */ |
| 202 this.status = xhr.status; | 298 this.status = xhr.status; |
| 203 | 299 |
| 204 /** | 300 /** |
| 205 * The HTTP status description. | 301 * The HTTP status description. |
| 206 * @const {string} | 302 * @const {string} |
| 207 */ | 303 */ |
| 208 this.statusText = xhr.statusText; | 304 this.statusText = xhr.statusText; |
| 209 | 305 |
| 210 /** | 306 /** |
| 211 * The response URL, if any. | 307 * The response URL, if any. |
| 212 * @const {?string} | 308 * @const {?string} |
| 213 */ | 309 */ |
| 214 this.url = xhr.responseURL; | 310 this.url = xhr.responseURL; |
| 215 | 311 |
| 216 /** @private {string} */ | 312 /** @private {string} */ |
| 217 this.text_ = xhr.responseText || ''; | 313 this.text_ = xhr.responseText || ''; |
| 314 |
| 315 /** @private {*|undefined} */ |
| 316 this.json_ = undefined; |
| 218 }; | 317 }; |
| 219 | 318 |
| 220 /** | 319 /** |
| 221 * @return {string} The text content of the response. | 320 * @return {string} The text content of the response. |
| 222 */ | 321 */ |
| 223 remoting.Xhr.Response.prototype.getText = function() { | 322 remoting.Xhr.Response.prototype.getText = function() { |
| 224 return this.text_; | 323 return this.text_; |
| 225 }; | 324 }; |
| 226 | 325 |
| 227 /** | 326 /** |
| 327 * Get the JSON content of the response. Requires acceptJson to have |
| 328 * been true in the request. |
| 228 * @return {*} The parsed JSON content of the response. | 329 * @return {*} The parsed JSON content of the response. |
| 229 */ | 330 */ |
| 230 remoting.Xhr.Response.prototype.getJson = function() { | 331 remoting.Xhr.Response.prototype.getJson = function() { |
| 231 base.debug.assert(this.type_ == remoting.Xhr.ResponseType.JSON); | 332 base.debug.assert(this.allowJson_); |
| 232 return JSON.parse(this.text_); | 333 if (this.json_ === undefined) { |
| 334 this.json_ = JSON.parse(this.text_); |
| 335 } |
| 336 return this.json_; |
| 233 }; | 337 }; |
| 234 | 338 |
| 235 /** | 339 /** |
| 236 * Returns a copy of the input object with all null or undefined | 340 * Returns a copy of the input object with all null or undefined |
| 237 * fields removed. | 341 * fields removed. |
| 238 * | 342 * |
| 239 * @param {Object<string,?string>|undefined} input | 343 * @param {Object<string,?string>|undefined} input |
| 240 * @return {!Object<string,string>} | 344 * @return {!Object<string,string>} |
| 241 * @private | 345 * @private |
| 242 */ | 346 */ |
| (...skipping 21 matching lines...) Expand all Loading... |
| 264 var paramArray = []; | 368 var paramArray = []; |
| 265 for (var key in paramHash) { | 369 for (var key in paramHash) { |
| 266 paramArray.push(encodeURIComponent(key) + | 370 paramArray.push(encodeURIComponent(key) + |
| 267 '=' + encodeURIComponent(paramHash[key])); | 371 '=' + encodeURIComponent(paramHash[key])); |
| 268 } | 372 } |
| 269 if (paramArray.length > 0) { | 373 if (paramArray.length > 0) { |
| 270 return paramArray.join('&'); | 374 return paramArray.join('&'); |
| 271 } | 375 } |
| 272 return ''; | 376 return ''; |
| 273 }; | 377 }; |
| 274 | |
| 275 /** | |
| 276 * Generic success/failure response proxy. | |
| 277 * | |
| 278 * TODO(jrw): Stop using this and move default error handling directly | |
| 279 * into Xhr class. | |
| 280 * | |
| 281 * @param {function():void} onDone | |
| 282 * @param {function(!remoting.Error):void} onError | |
| 283 * @param {Array<remoting.Error.Tag>=} opt_ignoreErrors | |
| 284 * @return {function(!remoting.Xhr.Response):void} | |
| 285 */ | |
| 286 remoting.Xhr.defaultResponse = function(onDone, onError, opt_ignoreErrors) { | |
| 287 /** @param {!remoting.Xhr.Response} response */ | |
| 288 var result = function(response) { | |
| 289 var error = remoting.Error.fromHttpStatus(response.status); | |
| 290 if (error.isNone()) { | |
| 291 onDone(); | |
| 292 return; | |
| 293 } | |
| 294 | |
| 295 if (opt_ignoreErrors && error.hasTag.apply(error, opt_ignoreErrors)) { | |
| 296 onDone(); | |
| 297 return; | |
| 298 } | |
| 299 | |
| 300 onError(error); | |
| 301 }; | |
| 302 return result; | |
| 303 }; | |
| OLD | NEW |