Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(63)

Side by Side Diff: remoting/webapp/crd/js/xhr.js

Issue 1028683004: Added better error and OAuth support in xhr.js. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 5 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
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 21
25 /** @private @const */ 22 /** @private @const */
26 this.responseType_ = params.responseType || remoting.Xhr.ResponseType.TEXT; 23 this.ignoreErrors_ = params.ignoreErrors || null;
27 24
28 // Apply URL parameters. 25 // Apply URL parameters.
29 var url = params.url; 26 var url = params.url;
30 var parameterString = ''; 27 var parameterString = '';
31 if (typeof(params.urlParams) === 'string') { 28 if (typeof(params.urlParams) === 'string') {
32 parameterString = params.urlParams; 29 parameterString = params.urlParams;
33 } else if (typeof(params.urlParams) === 'object') { 30 } else if (typeof(params.urlParams) === 'object') {
34 parameterString = remoting.Xhr.urlencodeParamHash( 31 parameterString = remoting.Xhr.urlencodeParamHash(
35 remoting.Xhr.removeNullFields_(params.urlParams)); 32 remoting.Xhr.removeNullFields_(params.urlParams));
36 } 33 }
37 if (parameterString) { 34 if (parameterString) {
38 base.debug.assert(url.indexOf('?') == -1);
39 url += '?' + parameterString; 35 url += '?' + parameterString;
40 } 36 }
41 37
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. 38 // Prepare the build modified headers.
51 var headers = remoting.Xhr.removeNullFields_(params.headers); 39 /** @const */
40 this.headers_ = remoting.Xhr.removeNullFields_(params.headers);
52 41
53 // Convert the content fields to a single text content variable. 42 // Convert the content fields to a single text content variable.
54 /** @private {?string} */ 43 /** @private {?string} */
55 this.content_ = null; 44 this.content_ = null;
56 if (params.textContent !== undefined) { 45 if (params.textContent !== undefined) {
46 this.maybeSetContentType_('text/plain');
57 this.content_ = params.textContent; 47 this.content_ = params.textContent;
58 } else if (params.formContent !== undefined) { 48 } else if (params.formContent !== undefined) {
59 if (!('Content-type' in headers)) { 49 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); 50 this.content_ = remoting.Xhr.urlencodeParamHash(params.formContent);
63 } else if (params.jsonContent !== undefined) { 51 } else if (params.jsonContent !== undefined) {
64 if (!('Content-type' in headers)) { 52 this.maybeSetContentType_('application/json');
65 headers['Content-type'] = 'application/json; charset=UTF-8';
66 }
67 this.content_ = JSON.stringify(params.jsonContent); 53 this.content_ = JSON.stringify(params.jsonContent);
68 } 54 }
69 55
70 // Apply the oauthToken field. 56 // Apply the oauthToken field.
71 if (params.oauthToken !== undefined) { 57 if (params.oauthToken !== undefined) {
72 base.debug.assert(!('Authorization' in headers)); 58 this.setAuthToken_(params.oauthToken);
73 headers['Authorization'] = 'Bearer ' + params.oauthToken;
74 } 59 }
75 60
61 /** @private @const {boolean} */
62 this.acceptJson_ = params.acceptJson || false;
63 if (this.acceptJson_) {
64 this.maybeSetHeader_('Accept', 'application/json');
65 }
66
67 // Apply useIdentity field.
68 /** @const {boolean} */
69 this.useIdentity_ = params.useIdentity || false;
70
71 /** @private @const {!XMLHttpRequest} */
72 this.nativeXhr_ = new XMLHttpRequest();
73 this.nativeXhr_.onreadystatechange = this.onReadyStateChange_.bind(this);
74 this.nativeXhr_.withCredentials = params.withCredentials || false;
76 this.nativeXhr_.open(params.method, url, true); 75 this.nativeXhr_.open(params.method, url, true);
77 for (var key in headers) {
78 this.nativeXhr_.setRequestHeader(key, headers[key]);
79 }
80 76
81 /** @private {base.Deferred<!remoting.Xhr.Response>} */ 77 /** @private {base.Deferred<!remoting.Xhr.Response>} */
82 this.deferred_ = null; 78 this.deferred_ = null;
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 * ignoreErrors: List of error types (arising from HTTP result codes)
111 * to ignore. If null (the default) no HTTP status code is
112 * treated as an error.
113 *
114 * acceptJson: If true, send an Accept header indicating that a JSON
115 * response is expected.
124 * 116 *
125 * @typedef {{ 117 * @typedef {{
126 * method: string, 118 * method: string,
127 * url:string, 119 * url:string,
128 * urlParams:(string|Object<string,?string>|undefined), 120 * urlParams:(string|Object<string,?string>|undefined),
129 * textContent:(string|undefined), 121 * textContent:(string|undefined),
130 * formContent:(Object|undefined), 122 * formContent:(Object|undefined),
131 * jsonContent:(*|undefined), 123 * jsonContent:(*|undefined),
132 * headers:(Object<string,?string>|undefined), 124 * headers:(Object<string,?string>|undefined),
133 * withCredentials:(boolean|undefined), 125 * withCredentials:(boolean|undefined),
134 * oauthToken:(string|undefined), 126 * oauthToken:(string|undefined),
135 * responseType:(remoting.Xhr.ResponseType|undefined) 127 * useIdentity:(boolean|undefined),
128 * ignoreErrors:(Array<remoting.Error.Tag>|undefined),
129 * acceptJson:(boolean|undefined)
136 * }} 130 * }}
137 */ 131 */
138 remoting.Xhr.Params; 132 remoting.Xhr.Params;
139 133
140 /** 134 /**
141 * Aborts the HTTP request. Does nothing is the request has finished 135 * Aborts the HTTP request. Does nothing is the request has finished
142 * already. 136 * already.
143 */ 137 */
144 remoting.Xhr.prototype.abort = function() { 138 remoting.Xhr.prototype.abort = function() {
145 this.nativeXhr_.abort(); 139 this.nativeXhr_.abort();
146 }; 140 };
147 141
148 /** 142 /**
149 * Starts and HTTP request and gets a promise that is resolved when 143 * Starts and HTTP request and gets a promise that is resolved when
150 * the request completes. 144 * the request completes.
151 * 145 *
152 * Any error that prevents receiving an HTTP status 146 * Any error that prevents receiving an HTTP status
153 * code causes this promise to be rejected. 147 * code causes this promise to be rejected.
154 * 148 *
155 * NOTE: Calling this method more than once will return the same 149 * NOTE: Calling this method more than once will return the same
156 * promise and not start a new request, despite what the name 150 * promise and not start a new request, despite what the name
157 * suggests. 151 * suggests.
158 * 152 *
159 * @return {!Promise<!remoting.Xhr.Response>} 153 * @return {!Promise<!remoting.Xhr.Response>}
160 */ 154 */
161 remoting.Xhr.prototype.start = function() { 155 remoting.Xhr.prototype.start = function() {
162 if (this.deferred_ == null) { 156 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(); 157 this.deferred_ = new base.Deferred();
158
159 // Send the XHR, possibly after getting an OAuth token.
160 var self = this;
161 if (this.useIdentity_) {
162 remoting.identity.getToken().then(function(token) {
163 self.setAuthToken_(token);
164 self.sendXhr_();
165 }, this.deferred_.reject.bind(this.deferred_));
166 } else {
167 this.sendXhr_();
168 }
167 } 169 }
168 return this.deferred_.promise(); 170 return this.deferred_.promise();
169 }; 171 };
170 172
171 /** 173 /**
174 * @param {remoting.Xhr.Params} params
175 * @throws {Error} if params are invalid
176 */
177 remoting.Xhr.checkParams_ = function(params) {
178 if (params.urlParams) {
179 if (params.url.indexOf('?') != -1) {
180 throw new Error('URL may not contain "?" when urlParams is set');
181 }
182 if (params.url.indexOf('#') != -1) {
183 throw new Error('URL may not contain "#" when urlParams is set');
184 }
185 }
186
187 if ((Number(params.textContent !== undefined) +
188 Number(params.formContent !== undefined) +
189 Number(params.jsonContent !== undefined)) > 1) {
190 throw new Error(
191 'may only specify one of textContent, formContent, and jsonContent');
192 }
193
194 if (params.useIdentity && params.oauthToken !== undefined) {
195 throw new Error('may not specify both useIdentity and oauthToken');
196 }
197
198 if ((params.useIdentity || params.oauthToken !== undefined) &&
199 params.headers &&
200 params.headers['Authorization'] != null) {
201 throw new Error(
202 'may not specify useIdentity or oauthToken ' +
203 'with an Authorization header');
204 }
205 };
206
207 /**
208 * @param {string} token
209 * @private
210 */
211 remoting.Xhr.prototype.setAuthToken_ = function(token) {
212 this.setHeader_('Authorization', 'Bearer ' + token);
213 };
214
215 /**
216 * @param {string} type
217 * @private
218 */
219 remoting.Xhr.prototype.maybeSetContentType_ = function(type) {
220 this.maybeSetHeader_('Content-type', type + '; charset=UTF-8');
221 };
222
223 /**
224 * @param {string} key
225 * @param {string} value
226 * @private
227 */
228 remoting.Xhr.prototype.setHeader_ = function(key, value) {
229 var wasSet = this.maybeSetHeader_(key, value);
230 base.debug.assert(wasSet);
231 };
232
233 /**
234 * @param {string} key
235 * @param {string} value
236 * @return {boolean}
237 * @private
238 */
239 remoting.Xhr.prototype.maybeSetHeader_ = function(key, value) {
240 if (!(key in this.headers_)) {
241 this.headers_[key] = value;
242 return true;
243 }
244 return false;
245 };
246
247 /** @private */
248 remoting.Xhr.prototype.sendXhr_ = function() {
249 for (var key in this.headers_) {
250 this.nativeXhr_.setRequestHeader(key, this.headers_[key]);
251 }
252 this.nativeXhr_.send(this.content_);
253 this.content_ = null; // for gc
254 };
255
256 /**
172 * @private 257 * @private
173 */ 258 */
174 remoting.Xhr.prototype.onReadyStateChange_ = function() { 259 remoting.Xhr.prototype.onReadyStateChange_ = function() {
175 var xhr = this.nativeXhr_; 260 var xhr = this.nativeXhr_;
176 if (xhr.readyState == 4) { 261 if (xhr.readyState == 4) {
177 // See comments at remoting.Xhr.Response. 262 var error = remoting.Error.fromHttpStatus(xhr.status);
178 this.deferred_.resolve(new remoting.Xhr.Response(xhr, this.responseType_)); 263 if (error.isNone() ||
264 this.ignoreErrors_ == null ||
265 error.hasTag.apply(error, this.ignoreErrors_)) {
266 // See comments at remoting.Xhr.Response.
267 this.deferred_.resolve(new remoting.Xhr.Response(
268 xhr, this.acceptJson_));
269 } else {
270 this.deferred_.reject(error);
271 }
179 } 272 }
180 }; 273 };
181 274
182 /** 275 /**
183 * The response-related parts of an XMLHttpRequest. Note that this 276 * The response-related parts of an XMLHttpRequest. Note that this
184 * class is not just a facade for XMLHttpRequest; it saves the value 277 * class is not just a facade for XMLHttpRequest; it saves the value
185 * of the |responseText| field becuase once onReadyStateChange_ 278 * of the |responseText| field becuase once onReadyStateChange_
186 * (above) returns, the value of |responseText| is reset to the empty 279 * (above) returns, the value of |responseText| is reset to the empty
187 * string! This is a documented anti-feature of the XMLHttpRequest 280 * string! This is a documented anti-feature of the XMLHttpRequest
188 * API. 281 * API.
189 * 282 *
190 * @constructor 283 * @constructor
191 * @param {!XMLHttpRequest} xhr 284 * @param {!XMLHttpRequest} xhr
192 * @param {remoting.Xhr.ResponseType} type 285 * @param {boolean} allowJson
193 */ 286 */
194 remoting.Xhr.Response = function(xhr, type) { 287 remoting.Xhr.Response = function(xhr, allowJson) {
195 /** @private @const */ 288 /** @private @const */
196 this.type_ = type; 289 this.allowJson_ = allowJson;
197 290
198 /** 291 /**
199 * The HTTP status code. 292 * The HTTP status code.
200 * @const {number} 293 * @const {number}
201 */ 294 */
202 this.status = xhr.status; 295 this.status = xhr.status;
203 296
204 /** 297 /**
205 * The HTTP status description. 298 * The HTTP status description.
206 * @const {string} 299 * @const {string}
(...skipping 11 matching lines...) Expand all
218 }; 311 };
219 312
220 /** 313 /**
221 * @return {string} The text content of the response. 314 * @return {string} The text content of the response.
222 */ 315 */
223 remoting.Xhr.Response.prototype.getText = function() { 316 remoting.Xhr.Response.prototype.getText = function() {
224 return this.text_; 317 return this.text_;
225 }; 318 };
226 319
227 /** 320 /**
321 * Get the JSON content of the response. Requires acceptJson to have
322 * been true in the request.
228 * @return {*} The parsed JSON content of the response. 323 * @return {*} The parsed JSON content of the response.
229 */ 324 */
230 remoting.Xhr.Response.prototype.getJson = function() { 325 remoting.Xhr.Response.prototype.getJson = function() {
231 base.debug.assert(this.type_ == remoting.Xhr.ResponseType.JSON); 326 base.debug.assert(this.allowJson_);
232 return JSON.parse(this.text_); 327 return JSON.parse(this.text_);
233 }; 328 };
234 329
235 /** 330 /**
236 * Returns a copy of the input object with all null or undefined 331 * Returns a copy of the input object with all null or undefined
237 * fields removed. 332 * fields removed.
238 * 333 *
239 * @param {Object<string,?string>|undefined} input 334 * @param {Object<string,?string>|undefined} input
240 * @return {!Object<string,string>} 335 * @return {!Object<string,string>}
241 * @private 336 * @private
(...skipping 22 matching lines...) Expand all
264 var paramArray = []; 359 var paramArray = [];
265 for (var key in paramHash) { 360 for (var key in paramHash) {
266 paramArray.push(encodeURIComponent(key) + 361 paramArray.push(encodeURIComponent(key) +
267 '=' + encodeURIComponent(paramHash[key])); 362 '=' + encodeURIComponent(paramHash[key]));
268 } 363 }
269 if (paramArray.length > 0) { 364 if (paramArray.length > 0) {
270 return paramArray.join('&'); 365 return paramArray.join('&');
271 } 366 }
272 return ''; 367 return '';
273 }; 368 };
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 };
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698