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; |
83 }; | 76 }; |
84 | 77 |
85 /** | 78 /** |
86 * @enum {string} | 79 * Parameters for the 'start' function. Unless otherwise noted, all |
87 */ | 80 * 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 * | 81 * |
97 * method: The HTTP method to use. | 82 * method: (required) The HTTP method to use. |
98 * | 83 * |
99 * url: The URL to request. | 84 * url: (required) The URL to request. |
100 * | 85 * |
101 * urlParams: (optional) Parameters to be appended to the URL. | 86 * urlParams: Parameters to be appended to the URL. Null-valued |
102 * Null-valued parameters are omitted. | 87 * parameters are omitted. |
103 * | 88 * |
104 * textContent: (optional) Text to be sent as the request body. | 89 * textContent: Text to be sent as the request body. |
105 * | 90 * |
106 * formContent: (optional) Data to be URL-encoded and sent as the | 91 * formContent: Data to be URL-encoded and sent as the request body. |
107 * request body. Causes Content-type header to be set | 92 * Causes Content-type header to be set appropriately. |
108 * appropriately. | |
109 * | 93 * |
110 * jsonContent: (optional) Data to be JSON-encoded and sent as the | 94 * jsonContent: Data to be JSON-encoded and sent as the request body. |
111 * request body. Causes Content-type header to be set | 95 * Causes Content-type header to be set appropriately. |
112 * appropriately. | |
113 * | 96 * |
114 * headers: (optional) Additional request headers to be sent. | 97 * headers: Additional request headers to be sent. Null-valued |
115 * Null-valued headers are omitted. | 98 * headers are omitted. |
116 * | 99 * |
117 * withCredentials: (optional) Value of the XHR's withCredentials field. | 100 * withCredentials: Value of the XHR's withCredentials field. |
118 * | 101 * |
119 * oauthToken: (optional) An OAuth2 token used to construct an | 102 * oauthToken: An OAuth2 token used to construct an Authentication |
120 * Authentication header. | 103 * header. |
121 * | 104 * |
122 * responseType: (optional) Request a response of a specific | 105 * useIdentity: Use identity API to get an OAuth2 token. |
123 * type. Default: TEXT. | 106 * |
| 107 * acceptJson: If true, send an Accept header indicating that a JSON |
| 108 * response is expected. |
124 * | 109 * |
125 * @typedef {{ | 110 * @typedef {{ |
126 * method: string, | 111 * method: string, |
127 * url:string, | 112 * url:string, |
128 * urlParams:(string|Object<string,?string>|undefined), | 113 * urlParams:(string|Object<string,?string>|undefined), |
129 * textContent:(string|undefined), | 114 * textContent:(string|undefined), |
130 * formContent:(Object|undefined), | 115 * formContent:(Object|undefined), |
131 * jsonContent:(*|undefined), | 116 * jsonContent:(*|undefined), |
132 * headers:(Object<string,?string>|undefined), | 117 * headers:(Object<string,?string>|undefined), |
133 * withCredentials:(boolean|undefined), | 118 * withCredentials:(boolean|undefined), |
134 * oauthToken:(string|undefined), | 119 * oauthToken:(string|undefined), |
135 * responseType:(remoting.Xhr.ResponseType|undefined) | 120 * useIdentity:(boolean|undefined), |
| 121 * acceptJson:(boolean|undefined) |
136 * }} | 122 * }} |
137 */ | 123 */ |
138 remoting.Xhr.Params; | 124 remoting.Xhr.Params; |
139 | 125 |
140 /** | 126 /** |
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 | 127 * Starts and HTTP request and gets a promise that is resolved when |
150 * the request completes. | 128 * the request completes. |
151 * | 129 * |
152 * Any error that prevents receiving an HTTP status | 130 * Any error that prevents sending the request causes the promise to |
153 * code causes this promise to be rejected. | 131 * be rejected. |
154 * | 132 * |
155 * NOTE: Calling this method more than once will return the same | 133 * NOTE: Calling this method more than once will return the same |
156 * promise and not start a new request, despite what the name | 134 * promise and not start a new request, despite what the name |
157 * suggests. | 135 * suggests. |
158 * | 136 * |
159 * @return {!Promise<!remoting.Xhr.Response>} | 137 * @return {!Promise<!remoting.Xhr.Response>} |
160 */ | 138 */ |
161 remoting.Xhr.prototype.start = function() { | 139 remoting.Xhr.prototype.start = function() { |
162 if (this.deferred_ == null) { | 140 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(); | 141 this.deferred_ = new base.Deferred(); |
| 142 |
| 143 // Send the XHR, possibly after getting an OAuth token. |
| 144 var that = this; |
| 145 if (this.useIdentity_) { |
| 146 remoting.identity.getToken().then(function(token) { |
| 147 base.debug.assert(that.nativeXhr_.readyState == 1); |
| 148 that.setAuthToken_(token); |
| 149 that.sendXhr_(); |
| 150 }).catch(function(error) { |
| 151 that.deferred_.reject(error); |
| 152 }); |
| 153 } else { |
| 154 this.sendXhr_(); |
| 155 } |
167 } | 156 } |
168 return this.deferred_.promise(); | 157 return this.deferred_.promise(); |
169 }; | 158 }; |
170 | 159 |
171 /** | 160 /** |
| 161 * @param {remoting.Xhr.Params} params |
| 162 * @throws {Error} if params are invalid |
| 163 */ |
| 164 remoting.Xhr.checkParams_ = function(params) { |
| 165 if (params.urlParams) { |
| 166 if (params.url.indexOf('?') != -1) { |
| 167 throw new Error('URL may not contain "?" when urlParams is set'); |
| 168 } |
| 169 if (params.url.indexOf('#') != -1) { |
| 170 throw new Error('URL may not contain "#" when urlParams is set'); |
| 171 } |
| 172 } |
| 173 |
| 174 if ((Number(params.textContent !== undefined) + |
| 175 Number(params.formContent !== undefined) + |
| 176 Number(params.jsonContent !== undefined)) > 1) { |
| 177 throw new Error( |
| 178 'may only specify one of textContent, formContent, and jsonContent'); |
| 179 } |
| 180 |
| 181 if (params.useIdentity && params.oauthToken !== undefined) { |
| 182 throw new Error('may not specify both useIdentity and oauthToken'); |
| 183 } |
| 184 |
| 185 if ((params.useIdentity || params.oauthToken !== undefined) && |
| 186 params.headers && |
| 187 params.headers['Authorization'] != null) { |
| 188 throw new Error( |
| 189 'may not specify useIdentity or oauthToken ' + |
| 190 'with an Authorization header'); |
| 191 } |
| 192 }; |
| 193 |
| 194 /** |
| 195 * @param {string} token |
| 196 * @private |
| 197 */ |
| 198 remoting.Xhr.prototype.setAuthToken_ = function(token) { |
| 199 this.setHeader_('Authorization', 'Bearer ' + token); |
| 200 }; |
| 201 |
| 202 /** |
| 203 * @param {string} type |
| 204 * @private |
| 205 */ |
| 206 remoting.Xhr.prototype.maybeSetContentType_ = function(type) { |
| 207 this.maybeSetHeader_('Content-type', type + '; charset=UTF-8'); |
| 208 }; |
| 209 |
| 210 /** |
| 211 * @param {string} key |
| 212 * @param {string} value |
| 213 * @private |
| 214 */ |
| 215 remoting.Xhr.prototype.setHeader_ = function(key, value) { |
| 216 var wasSet = this.maybeSetHeader_(key, value); |
| 217 base.debug.assert(wasSet); |
| 218 }; |
| 219 |
| 220 /** |
| 221 * @param {string} key |
| 222 * @param {string} value |
| 223 * @return {boolean} |
| 224 * @private |
| 225 */ |
| 226 remoting.Xhr.prototype.maybeSetHeader_ = function(key, value) { |
| 227 if (!(key in this.headers_)) { |
| 228 this.headers_[key] = value; |
| 229 return true; |
| 230 } |
| 231 return false; |
| 232 }; |
| 233 |
| 234 /** @private */ |
| 235 remoting.Xhr.prototype.sendXhr_ = function() { |
| 236 for (var key in this.headers_) { |
| 237 this.nativeXhr_.setRequestHeader(key, this.headers_[key]); |
| 238 } |
| 239 this.nativeXhr_.send(this.content_); |
| 240 this.content_ = null; // for gc |
| 241 }; |
| 242 |
| 243 /** |
172 * @private | 244 * @private |
173 */ | 245 */ |
174 remoting.Xhr.prototype.onReadyStateChange_ = function() { | 246 remoting.Xhr.prototype.onReadyStateChange_ = function() { |
175 var xhr = this.nativeXhr_; | 247 var xhr = this.nativeXhr_; |
176 if (xhr.readyState == 4) { | 248 if (xhr.readyState == 4) { |
177 // See comments at remoting.Xhr.Response. | 249 // See comments at remoting.Xhr.Response. |
178 this.deferred_.resolve(new remoting.Xhr.Response(xhr, this.responseType_)); | 250 this.deferred_.resolve(new remoting.Xhr.Response( |
| 251 xhr, this.acceptJson_)); |
179 } | 252 } |
180 }; | 253 }; |
181 | 254 |
182 /** | 255 /** |
183 * The response-related parts of an XMLHttpRequest. Note that this | 256 * The response-related parts of an XMLHttpRequest. Note that this |
184 * class is not just a facade for XMLHttpRequest; it saves the value | 257 * class is not just a facade for XMLHttpRequest; it saves the value |
185 * of the |responseText| field becuase once onReadyStateChange_ | 258 * of the |responseText| field becuase once onReadyStateChange_ |
186 * (above) returns, the value of |responseText| is reset to the empty | 259 * (above) returns, the value of |responseText| is reset to the empty |
187 * string! This is a documented anti-feature of the XMLHttpRequest | 260 * string! This is a documented anti-feature of the XMLHttpRequest |
188 * API. | 261 * API. |
189 * | 262 * |
190 * @constructor | 263 * @constructor |
191 * @param {!XMLHttpRequest} xhr | 264 * @param {!XMLHttpRequest} xhr |
192 * @param {remoting.Xhr.ResponseType} type | 265 * @param {boolean} allowJson |
193 */ | 266 */ |
194 remoting.Xhr.Response = function(xhr, type) { | 267 remoting.Xhr.Response = function(xhr, allowJson) { |
195 /** @private @const */ | 268 /** @private @const */ |
196 this.type_ = type; | 269 this.allowJson_ = allowJson; |
197 | 270 |
198 /** | 271 /** |
199 * The HTTP status code. | 272 * The HTTP status code. |
200 * @const {number} | 273 * @const {number} |
201 */ | 274 */ |
202 this.status = xhr.status; | 275 this.status = xhr.status; |
203 | 276 |
204 /** | 277 /** |
205 * The HTTP status description. | 278 * The HTTP status description. |
206 * @const {string} | 279 * @const {string} |
207 */ | 280 */ |
208 this.statusText = xhr.statusText; | 281 this.statusText = xhr.statusText; |
209 | 282 |
210 /** | 283 /** |
211 * The response URL, if any. | 284 * The response URL, if any. |
212 * @const {?string} | 285 * @const {?string} |
213 */ | 286 */ |
214 this.url = xhr.responseURL; | 287 this.url = xhr.responseURL; |
215 | 288 |
216 /** @private {string} */ | 289 /** @private {string} */ |
217 this.text_ = xhr.responseText || ''; | 290 this.text_ = xhr.responseText || ''; |
| 291 |
| 292 /** @private {*|undefined} */ |
| 293 this.json_ = undefined; |
218 }; | 294 }; |
219 | 295 |
220 /** | 296 /** |
221 * @return {string} The text content of the response. | 297 * @return {string} The text content of the response. |
222 */ | 298 */ |
223 remoting.Xhr.Response.prototype.getText = function() { | 299 remoting.Xhr.Response.prototype.getText = function() { |
224 return this.text_; | 300 return this.text_; |
225 }; | 301 }; |
226 | 302 |
227 /** | 303 /** |
| 304 * Get the JSON content of the response. Requires acceptJson to have |
| 305 * been true in the request. |
228 * @return {*} The parsed JSON content of the response. | 306 * @return {*} The parsed JSON content of the response. |
229 */ | 307 */ |
230 remoting.Xhr.Response.prototype.getJson = function() { | 308 remoting.Xhr.Response.prototype.getJson = function() { |
231 base.debug.assert(this.type_ == remoting.Xhr.ResponseType.JSON); | 309 base.debug.assert(this.allowJson_); |
232 return JSON.parse(this.text_); | 310 if (this.json_ === undefined) { |
| 311 this.json_ = JSON.parse(this.text_); |
| 312 } |
| 313 return this.json_; |
233 }; | 314 }; |
234 | 315 |
235 /** | 316 /** |
236 * Returns a copy of the input object with all null or undefined | 317 * Returns a copy of the input object with all null or undefined |
237 * fields removed. | 318 * fields removed. |
238 * | 319 * |
239 * @param {Object<string,?string>|undefined} input | 320 * @param {Object<string,?string>|undefined} input |
240 * @return {!Object<string,string>} | 321 * @return {!Object<string,string>} |
241 * @private | 322 * @private |
242 */ | 323 */ |
(...skipping 21 matching lines...) Expand all Loading... |
264 var paramArray = []; | 345 var paramArray = []; |
265 for (var key in paramHash) { | 346 for (var key in paramHash) { |
266 paramArray.push(encodeURIComponent(key) + | 347 paramArray.push(encodeURIComponent(key) + |
267 '=' + encodeURIComponent(paramHash[key])); | 348 '=' + encodeURIComponent(paramHash[key])); |
268 } | 349 } |
269 if (paramArray.length > 0) { | 350 if (paramArray.length > 0) { |
270 return paramArray.join('&'); | 351 return paramArray.join('&'); |
271 } | 352 } |
272 return ''; | 353 return ''; |
273 }; | 354 }; |
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 |