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

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

Issue 1003433002: Updated remoting.xhr API to use promises. Removed access to the native (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@spy-promise
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 * 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 {string} */
20 * Takes an associative array of parameters and urlencodes it. 28 this.responseType_ = params.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 * Values produced by a request.
151 *
152 * status: The HTTP status code.
153 *
154 * statusText: The HTTP status description.
155 *
156 * responseUrl: The response URL, if any.
157 *
158 * responseText: The content of the response as a string. Valid only
159 * if responseType is set to TEXT or the request failed.
160 *
161 * responseJson: The content of the response as a parsed JSON value.
162 * Valid only if the request succeeded and the responseType is set
163 * to JSON.
164 *
165 * @typedef {{
166 * status:number,
167 * statusText:string,
168 * responseUrl:string,
169 * textContent:string,
170 * jsonContent:*
171 * }}
172 */
173 remoting.Xhr.Response;
kelvinp 2015/03/17 01:32:46 Why is this needed?
John Williams 2015/03/17 17:39:38 I'm not sure I understand the question. Are you a
174
175 /**
176 * Aborts the HTTP request. Does nothing is the request has finished
177 * already.
178 */
179 remoting.Xhr.prototype.abort = function() {
180 return this.nativeXhr_.abort();
181 };
182
183 /**
184 * Gets a promise that is resolved when the request completes.
185 *
186 * If an HTTP status code outside the 200..299 range is returned, the
187 * promise is rejected with a remoting.Error by default. Setting
188 * resolveOnErrorStatus to true in the constructor parameters allows
189 * the promise to resolve for any HTTP status code.
190 *
191 * Any error that prevents the HTTP request from succeeding causes
192 * this promise to be rejected.
193 *
194 * NOTE: Calling this method more than once will return the same
195 * promise and not start a new request, despite what the name
196 * suggests.
197 *
198 * @return {!Promise<!remoting.Xhr.Response>}
199 */
200 remoting.Xhr.prototype.start = function() {
201 if (this.deferred_ == null) {
202 var xhr = this.nativeXhr_;
203 xhr.send(this.content_);
204 this.content_ = null; // for gc
205 this.deferred_ = new base.Deferred();
206 }
207 return this.deferred_.promise();
208 };
209
210 /**
211 * @private
212 */
213 remoting.Xhr.prototype.onReadyStateChange_ = function() {
214 var xhr = this.nativeXhr_;
215
216 if (xhr.readyState != 4) {
217 return;
218 }
219
220 var succeeded = 200 <= xhr.status && xhr.status < 300;
221 var response = {
222 status: xhr.status,
223 statusText: xhr.statusText,
224 responseUrl: xhr.responseURL,
225 responseText: !succeeded ||
226 this.responseType_ == remoting.Xhr.ResponseType.TEXT ?
227 xhr.responseText : '<invalid responseText>',
228 responseJson: succeeded &&
229 this.responseType_ == remoting.Xhr.ResponseType.JSON ?
230 xhr.response : ['<invalid responseJson>']
231 };
232 this.deferred_.resolve(response);
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.
277 * TODO(jrw): Stop using this.
200 * 278 *
201 * @param {function():void} onDone 279 * @param {function():void} onDone
202 * @param {function(!remoting.Error):void} onError 280 * @param {function(!remoting.Error):void} onError
203 * @param {Array<remoting.Error.Tag>=} opt_ignoreErrors 281 * @param {Array<remoting.Error.Tag>=} opt_ignoreErrors
204 * @return {function(XMLHttpRequest):void} 282 * @return {function(remoting.Xhr.Response):void}
205 */ 283 */
206 remoting.xhr.defaultResponse = function(onDone, onError, opt_ignoreErrors) { 284 remoting.Xhr.defaultResponse = function(onDone, onError, opt_ignoreErrors) {
207 /** @param {XMLHttpRequest} xhr */ 285 /** @param {remoting.Xhr.Response} response */
208 var result = function(xhr) { 286 var result = function(response) {
209 var error = 287 var error = remoting.Error.fromHttpStatus(response.status);
210 remoting.Error.fromHttpStatus(/** @type {number} */ (xhr.status));
211 if (error.isNone()) { 288 if (error.isNone()) {
212 onDone(); 289 onDone();
213 return; 290 return;
214 } 291 }
215 292
216 if (opt_ignoreErrors && error.hasTag.apply(error, opt_ignoreErrors)) { 293 if (opt_ignoreErrors && error.hasTag.apply(error, opt_ignoreErrors)) {
217 onDone(); 294 onDone();
218 return; 295 return;
219 } 296 }
220 297
221 onError(error); 298 onError(error);
222 }; 299 };
223 return result; 300 return result;
224 }; 301 };
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698