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