RESTController.js 10 KB

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