RESTController.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 {
  56. v4: uuidv4
  57. } = require('uuid');
  58. let XHR = null;
  59. if (typeof XMLHttpRequest !== 'undefined') {
  60. XHR = XMLHttpRequest;
  61. }
  62. XHR = require('xmlhttprequest').XMLHttpRequest;
  63. let useXDomainRequest = false;
  64. if (typeof XDomainRequest !== 'undefined' && !('withCredentials' in new XMLHttpRequest())) {
  65. useXDomainRequest = true;
  66. }
  67. function ajaxIE9(method
  68. /*: string*/
  69. , url
  70. /*: string*/
  71. , data
  72. /*: any*/
  73. , headers
  74. /*:: ?: any*/
  75. , options
  76. /*:: ?: FullOptions*/
  77. ) {
  78. return new Promise((resolve, reject) => {
  79. const xdr = new XDomainRequest();
  80. xdr.onload = function () {
  81. let response;
  82. try {
  83. response = JSON.parse(xdr.responseText);
  84. } catch (e) {
  85. reject(e);
  86. }
  87. if (response) {
  88. resolve({
  89. response
  90. });
  91. }
  92. };
  93. xdr.onerror = xdr.ontimeout = function () {
  94. // Let's fake a real error message.
  95. const fakeResponse = {
  96. responseText: JSON.stringify({
  97. code: _ParseError.default.X_DOMAIN_REQUEST,
  98. error: "IE's XDomainRequest does not supply error info."
  99. })
  100. };
  101. reject(fakeResponse);
  102. };
  103. xdr.onprogress = function () {
  104. if (options && typeof options.progress === 'function') {
  105. options.progress(xdr.responseText);
  106. }
  107. };
  108. xdr.open(method, url);
  109. xdr.send(data);
  110. if (options && typeof options.requestTask === 'function') {
  111. options.requestTask(xdr);
  112. }
  113. });
  114. }
  115. const RESTController = {
  116. ajax(method
  117. /*: string*/
  118. , url
  119. /*: string*/
  120. , data
  121. /*: any*/
  122. , headers
  123. /*:: ?: any*/
  124. , options
  125. /*:: ?: FullOptions*/
  126. ) {
  127. if (useXDomainRequest) {
  128. return ajaxIE9(method, url, data, headers, options);
  129. }
  130. const promise = (0, _promiseUtils.resolvingPromise)();
  131. const isIdempotent = _CoreManager.default.get('IDEMPOTENCY') && ['POST', 'PUT'].includes(method);
  132. const requestId = isIdempotent ? uuidv4() : '';
  133. let attempts = 0;
  134. const dispatch = function () {
  135. if (XHR == null) {
  136. throw new Error('Cannot make a request: No definition of XMLHttpRequest was found.');
  137. }
  138. let handled = false;
  139. const xhr = new XHR();
  140. xhr.onreadystatechange = function () {
  141. if (xhr.readyState !== 4 || handled || xhr._aborted) {
  142. return;
  143. }
  144. handled = true;
  145. if (xhr.status >= 200 && xhr.status < 300) {
  146. let response;
  147. try {
  148. response = JSON.parse(xhr.responseText);
  149. if (typeof xhr.getResponseHeader === 'function') {
  150. if ((xhr.getAllResponseHeaders() || '').includes('x-parse-job-status-id: ')) {
  151. response = xhr.getResponseHeader('x-parse-job-status-id');
  152. }
  153. }
  154. } catch (e) {
  155. promise.reject(e.toString());
  156. }
  157. if (response) {
  158. promise.resolve({
  159. response,
  160. status: xhr.status,
  161. xhr
  162. });
  163. }
  164. } else if (xhr.status >= 500 || xhr.status === 0) {
  165. // retry on 5XX or node-xmlhttprequest error
  166. if (++attempts < _CoreManager.default.get('REQUEST_ATTEMPT_LIMIT')) {
  167. // Exponentially-growing random delay
  168. const delay = Math.round(Math.random() * 125 * Math.pow(2, attempts));
  169. setTimeout(dispatch, delay);
  170. } else if (xhr.status === 0) {
  171. promise.reject('Unable to connect to the Parse API');
  172. } else {
  173. // After the retry limit is reached, fail
  174. promise.reject(xhr);
  175. }
  176. } else {
  177. promise.reject(xhr);
  178. }
  179. };
  180. headers = headers || {};
  181. if (typeof headers['Content-Type'] !== 'string') {
  182. // Avoid pre-flight
  183. headers['Content-Type'] = 'text/plain';
  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 {
  262. context
  263. } = options;
  264. if (context !== undefined) {
  265. payload._context = context;
  266. }
  267. if (method !== 'POST') {
  268. payload._method = method;
  269. method = 'POST';
  270. }
  271. payload._ApplicationId = _CoreManager.default.get('APPLICATION_ID');
  272. const jsKey = _CoreManager.default.get('JAVASCRIPT_KEY');
  273. if (jsKey) {
  274. payload._JavaScriptKey = jsKey;
  275. }
  276. payload._ClientVersion = _CoreManager.default.get('VERSION');
  277. let {
  278. useMasterKey
  279. } = options;
  280. if (typeof useMasterKey === 'undefined') {
  281. useMasterKey = _CoreManager.default.get('USE_MASTER_KEY');
  282. }
  283. if (useMasterKey) {
  284. if (_CoreManager.default.get('MASTER_KEY')) {
  285. delete payload._JavaScriptKey;
  286. payload._MasterKey = _CoreManager.default.get('MASTER_KEY');
  287. }
  288. }
  289. if (_CoreManager.default.get('FORCE_REVOCABLE_SESSION')) {
  290. payload._RevocableSession = '1';
  291. }
  292. const {
  293. installationId
  294. } = options;
  295. let installationIdPromise;
  296. if (installationId && typeof installationId === 'string') {
  297. installationIdPromise = Promise.resolve(installationId);
  298. } else {
  299. const installationController = _CoreManager.default.getInstallationController();
  300. installationIdPromise = installationController.currentInstallationId();
  301. }
  302. return installationIdPromise.then(iid => {
  303. payload._InstallationId = iid;
  304. const userController = _CoreManager.default.getUserController();
  305. if (options && typeof options.sessionToken === 'string') {
  306. return Promise.resolve(options.sessionToken);
  307. }
  308. if (userController) {
  309. return userController.currentUserAsync().then(user => {
  310. if (user) {
  311. return Promise.resolve(user.getSessionToken());
  312. }
  313. return Promise.resolve(null);
  314. });
  315. }
  316. return Promise.resolve(null);
  317. }).then(token => {
  318. if (token) {
  319. payload._SessionToken = token;
  320. }
  321. const payloadString = JSON.stringify(payload);
  322. return RESTController.ajax(method, url, payloadString, {}, options).then(({
  323. response,
  324. status
  325. }) => {
  326. if (options.returnStatus) {
  327. return _objectSpread(_objectSpread({}, response), {}, {
  328. _status: status
  329. });
  330. }
  331. return response;
  332. });
  333. }).catch(RESTController.handleError);
  334. },
  335. handleError(response) {
  336. // Transform the error into an instance of ParseError by trying to parse
  337. // the error string as JSON
  338. let error;
  339. if (response && response.responseText) {
  340. try {
  341. const errorJSON = JSON.parse(response.responseText);
  342. error = new _ParseError.default(errorJSON.code, errorJSON.error);
  343. } catch (e) {
  344. // If we fail to parse the error text, that's okay.
  345. error = new _ParseError.default(_ParseError.default.INVALID_JSON, `Received an error with invalid JSON from Parse: ${response.responseText}`);
  346. }
  347. } else {
  348. const message = response.message ? response.message : response;
  349. error = new _ParseError.default(_ParseError.default.CONNECTION_FAILED, `XMLHttpRequest failed: ${JSON.stringify(message)}`);
  350. }
  351. return Promise.reject(error);
  352. },
  353. _setXHR(xhr
  354. /*: any*/
  355. ) {
  356. XHR = xhr;
  357. },
  358. _getXHR() {
  359. return XHR;
  360. }
  361. };
  362. module.exports = RESTController;