RESTController.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. "use strict";
  2. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  3. var _ParseError = _interopRequireDefault(require("./ParseError"));
  4. var _promiseUtils = require("./promiseUtils");
  5. function _interopRequireDefault(obj) {
  6. return obj && obj.__esModule ? obj : {
  7. default: obj
  8. };
  9. }
  10. function ownKeys(object, enumerableOnly) {
  11. var keys = Object.keys(object);
  12. if (Object.getOwnPropertySymbols) {
  13. var symbols = Object.getOwnPropertySymbols(object);
  14. enumerableOnly && (symbols = symbols.filter(function (sym) {
  15. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  16. })), keys.push.apply(keys, symbols);
  17. }
  18. return keys;
  19. }
  20. function _objectSpread(target) {
  21. for (var i = 1; i < arguments.length; i++) {
  22. var source = null != arguments[i] ? arguments[i] : {};
  23. i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
  24. _defineProperty(target, key, source[key]);
  25. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
  26. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  27. });
  28. }
  29. return target;
  30. }
  31. function _defineProperty(obj, key, value) {
  32. if (key in obj) {
  33. Object.defineProperty(obj, key, {
  34. value: value,
  35. enumerable: true,
  36. configurable: true,
  37. writable: true
  38. });
  39. } else {
  40. obj[key] = value;
  41. }
  42. return obj;
  43. }
  44. /**
  45. * Copyright (c) 2015-present, Parse, LLC.
  46. * All rights reserved.
  47. *
  48. * This source code is licensed under the BSD-style license found in the
  49. * LICENSE file in the root directory of this source tree. An additional grant
  50. * of patent rights can be found in the PATENTS file in the same directory.
  51. *
  52. * @flow
  53. */
  54. /* global XMLHttpRequest, XDomainRequest */
  55. const uuidv4 = require('./uuid');
  56. let XHR = null;
  57. if (typeof XMLHttpRequest !== 'undefined') {
  58. XHR = XMLHttpRequest;
  59. }
  60. XHR = require('xmlhttprequest').XMLHttpRequest;
  61. let useXDomainRequest = false;
  62. if (typeof XDomainRequest !== 'undefined' && !('withCredentials' in new XMLHttpRequest())) {
  63. useXDomainRequest = true;
  64. }
  65. function ajaxIE9(method
  66. /*: string*/
  67. , url
  68. /*: string*/
  69. , data
  70. /*: any*/
  71. , headers
  72. /*:: ?: any*/
  73. , options
  74. /*:: ?: FullOptions*/
  75. ) {
  76. return new Promise((resolve, reject) => {
  77. const xdr = new XDomainRequest();
  78. xdr.onload = function () {
  79. let response;
  80. try {
  81. response = JSON.parse(xdr.responseText);
  82. } catch (e) {
  83. reject(e);
  84. }
  85. if (response) {
  86. resolve({
  87. response
  88. });
  89. }
  90. };
  91. xdr.onerror = xdr.ontimeout = function () {
  92. // Let's fake a real error message.
  93. const fakeResponse = {
  94. responseText: JSON.stringify({
  95. code: _ParseError.default.X_DOMAIN_REQUEST,
  96. error: "IE's XDomainRequest does not supply error info."
  97. })
  98. };
  99. reject(fakeResponse);
  100. };
  101. xdr.onprogress = function () {
  102. if (options && typeof options.progress === 'function') {
  103. options.progress(xdr.responseText);
  104. }
  105. };
  106. xdr.open(method, url);
  107. xdr.send(data);
  108. if (options && typeof options.requestTask === 'function') {
  109. options.requestTask(xdr);
  110. }
  111. });
  112. }
  113. const RESTController = {
  114. ajax(method
  115. /*: string*/
  116. , url
  117. /*: string*/
  118. , data
  119. /*: any*/
  120. , headers
  121. /*:: ?: any*/
  122. , options
  123. /*:: ?: FullOptions*/
  124. ) {
  125. if (useXDomainRequest) {
  126. return ajaxIE9(method, url, data, headers, options);
  127. }
  128. const promise = (0, _promiseUtils.resolvingPromise)();
  129. const isIdempotent = _CoreManager.default.get('IDEMPOTENCY') && ['POST', 'PUT'].includes(method);
  130. const requestId = isIdempotent ? uuidv4() : '';
  131. let attempts = 0;
  132. const dispatch = function () {
  133. if (XHR == null) {
  134. throw new Error('Cannot make a request: No definition of XMLHttpRequest was found.');
  135. }
  136. let handled = false;
  137. const xhr = new XHR();
  138. xhr.onreadystatechange = function () {
  139. if (xhr.readyState !== 4 || handled || xhr._aborted) {
  140. return;
  141. }
  142. handled = true;
  143. if (xhr.status >= 200 && xhr.status < 300) {
  144. let response;
  145. try {
  146. response = JSON.parse(xhr.responseText);
  147. if (typeof xhr.getResponseHeader === 'function') {
  148. if ((xhr.getAllResponseHeaders() || '').includes('x-parse-job-status-id: ')) {
  149. response = xhr.getResponseHeader('x-parse-job-status-id');
  150. }
  151. if ((xhr.getAllResponseHeaders() || '').includes('x-parse-push-status-id: ')) {
  152. response = xhr.getResponseHeader('x-parse-push-status-id');
  153. }
  154. }
  155. } catch (e) {
  156. promise.reject(e.toString());
  157. }
  158. if (response) {
  159. promise.resolve({
  160. response,
  161. status: xhr.status,
  162. xhr
  163. });
  164. }
  165. } else if (xhr.status >= 500 || xhr.status === 0) {
  166. // retry on 5XX or node-xmlhttprequest error
  167. if (++attempts < _CoreManager.default.get('REQUEST_ATTEMPT_LIMIT')) {
  168. // Exponentially-growing random delay
  169. const delay = Math.round(Math.random() * 125 * Math.pow(2, attempts));
  170. setTimeout(dispatch, delay);
  171. } else if (xhr.status === 0) {
  172. promise.reject('Unable to connect to the Parse API');
  173. } else {
  174. // After the retry limit is reached, fail
  175. promise.reject(xhr);
  176. }
  177. } else {
  178. promise.reject(xhr);
  179. }
  180. };
  181. headers = headers || {};
  182. if (typeof headers['Content-Type'] !== 'string') {
  183. headers['Content-Type'] = 'text/plain'; // Avoid pre-flight
  184. }
  185. if (_CoreManager.default.get('IS_NODE')) {
  186. headers['User-Agent'] = 'Parse/' + _CoreManager.default.get('VERSION') + ' (NodeJS ' + process.versions.node + ')';
  187. }
  188. if (isIdempotent) {
  189. headers['X-Parse-Request-Id'] = requestId;
  190. }
  191. if (_CoreManager.default.get('SERVER_AUTH_TYPE') && _CoreManager.default.get('SERVER_AUTH_TOKEN')) {
  192. headers['Authorization'] = _CoreManager.default.get('SERVER_AUTH_TYPE') + ' ' + _CoreManager.default.get('SERVER_AUTH_TOKEN');
  193. }
  194. const customHeaders = _CoreManager.default.get('REQUEST_HEADERS');
  195. for (const key in customHeaders) {
  196. headers[key] = customHeaders[key];
  197. }
  198. function handleProgress(type, event) {
  199. if (options && typeof options.progress === 'function') {
  200. if (event.lengthComputable) {
  201. options.progress(event.loaded / event.total, event.loaded, event.total, {
  202. type
  203. });
  204. } else {
  205. options.progress(null, null, null, {
  206. type
  207. });
  208. }
  209. }
  210. }
  211. xhr.onprogress = event => {
  212. handleProgress('download', event);
  213. };
  214. if (xhr.upload) {
  215. xhr.upload.onprogress = event => {
  216. handleProgress('upload', event);
  217. };
  218. }
  219. xhr.open(method, url, true);
  220. for (const h in headers) {
  221. xhr.setRequestHeader(h, headers[h]);
  222. }
  223. xhr.onabort = function () {
  224. promise.resolve({
  225. response: {
  226. results: []
  227. },
  228. status: 0,
  229. xhr
  230. });
  231. };
  232. xhr.send(data);
  233. if (options && typeof options.requestTask === 'function') {
  234. options.requestTask(xhr);
  235. }
  236. };
  237. dispatch();
  238. return promise;
  239. },
  240. request(method
  241. /*: string*/
  242. , path
  243. /*: string*/
  244. , data
  245. /*: mixed*/
  246. , options
  247. /*:: ?: RequestOptions*/
  248. ) {
  249. options = options || {};
  250. let url = _CoreManager.default.get('SERVER_URL');
  251. if (url[url.length - 1] !== '/') {
  252. url += '/';
  253. }
  254. url += path;
  255. const payload = {};
  256. if (data && typeof data === 'object') {
  257. for (const k in data) {
  258. payload[k] = data[k];
  259. }
  260. } // Add context
  261. const context = options.context;
  262. if (context !== undefined) {
  263. payload._context = context;
  264. }
  265. if (method !== 'POST') {
  266. payload._method = method;
  267. method = 'POST';
  268. }
  269. payload._ApplicationId = _CoreManager.default.get('APPLICATION_ID');
  270. const jsKey = _CoreManager.default.get('JAVASCRIPT_KEY');
  271. if (jsKey) {
  272. payload._JavaScriptKey = jsKey;
  273. }
  274. payload._ClientVersion = _CoreManager.default.get('VERSION');
  275. let useMasterKey = options.useMasterKey;
  276. if (typeof useMasterKey === 'undefined') {
  277. useMasterKey = _CoreManager.default.get('USE_MASTER_KEY');
  278. }
  279. if (useMasterKey) {
  280. if (_CoreManager.default.get('MASTER_KEY')) {
  281. delete payload._JavaScriptKey;
  282. payload._MasterKey = _CoreManager.default.get('MASTER_KEY');
  283. } else {
  284. throw new Error('Cannot use the Master Key, it has not been provided.');
  285. }
  286. }
  287. if (_CoreManager.default.get('FORCE_REVOCABLE_SESSION')) {
  288. payload._RevocableSession = '1';
  289. }
  290. const installationId = options.installationId;
  291. let installationIdPromise;
  292. if (installationId && typeof installationId === 'string') {
  293. installationIdPromise = Promise.resolve(installationId);
  294. } else {
  295. const installationController = _CoreManager.default.getInstallationController();
  296. installationIdPromise = installationController.currentInstallationId();
  297. }
  298. return installationIdPromise.then(iid => {
  299. payload._InstallationId = iid;
  300. const userController = _CoreManager.default.getUserController();
  301. if (options && typeof options.sessionToken === 'string') {
  302. return Promise.resolve(options.sessionToken);
  303. } else if (userController) {
  304. return userController.currentUserAsync().then(user => {
  305. if (user) {
  306. return Promise.resolve(user.getSessionToken());
  307. }
  308. return Promise.resolve(null);
  309. });
  310. }
  311. return Promise.resolve(null);
  312. }).then(token => {
  313. if (token) {
  314. payload._SessionToken = token;
  315. }
  316. const payloadString = JSON.stringify(payload);
  317. return RESTController.ajax(method, url, payloadString, {}, options).then(({
  318. response,
  319. status
  320. }) => {
  321. if (options.returnStatus) {
  322. return _objectSpread(_objectSpread({}, response), {}, {
  323. _status: status
  324. });
  325. } else {
  326. return response;
  327. }
  328. });
  329. }).catch(RESTController.handleError);
  330. },
  331. handleError(response) {
  332. // Transform the error into an instance of ParseError by trying to parse
  333. // the error string as JSON
  334. let error;
  335. if (response && response.responseText) {
  336. try {
  337. const errorJSON = JSON.parse(response.responseText);
  338. error = new _ParseError.default(errorJSON.code, errorJSON.error);
  339. } catch (e) {
  340. // If we fail to parse the error text, that's okay.
  341. error = new _ParseError.default(_ParseError.default.INVALID_JSON, 'Received an error with invalid JSON from Parse: ' + response.responseText);
  342. }
  343. } else {
  344. const message = response.message ? response.message : response;
  345. error = new _ParseError.default(_ParseError.default.CONNECTION_FAILED, 'XMLHttpRequest failed: ' + JSON.stringify(message));
  346. }
  347. return Promise.reject(error);
  348. },
  349. _setXHR(xhr
  350. /*: any*/
  351. ) {
  352. XHR = xhr;
  353. },
  354. _getXHR() {
  355. return XHR;
  356. }
  357. };
  358. module.exports = RESTController;