ParseObject.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  1. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  7. var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
  8. var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
  9. var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
  10. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  11. var _canBeSerialized = _interopRequireDefault(require("./canBeSerialized"));
  12. var _decode = _interopRequireDefault(require("./decode"));
  13. var _encode = _interopRequireDefault(require("./encode"));
  14. var _escape2 = _interopRequireDefault(require("./escape"));
  15. var _EventuallyQueue = _interopRequireDefault(require("./EventuallyQueue"));
  16. var _ParseACL = _interopRequireDefault(require("./ParseACL"));
  17. var _parseDate = _interopRequireDefault(require("./parseDate"));
  18. var _ParseError = _interopRequireDefault(require("./ParseError"));
  19. var _ParseFile = _interopRequireDefault(require("./ParseFile"));
  20. var _promiseUtils = require("./promiseUtils");
  21. var _LocalDatastoreUtils = require("./LocalDatastoreUtils");
  22. var _ParseOp = require("./ParseOp");
  23. var _ParseQuery = _interopRequireDefault(require("./ParseQuery"));
  24. var _ParseRelation = _interopRequireDefault(require("./ParseRelation"));
  25. var SingleInstanceStateController = _interopRequireWildcard(require("./SingleInstanceStateController"));
  26. var _unique = _interopRequireDefault(require("./unique"));
  27. var UniqueInstanceStateController = _interopRequireWildcard(require("./UniqueInstanceStateController"));
  28. var _unsavedChildren = _interopRequireDefault(require("./unsavedChildren"));
  29. function _getRequireWildcardCache(nodeInterop) {
  30. if (typeof WeakMap !== "function") return null;
  31. var cacheBabelInterop = new WeakMap();
  32. var cacheNodeInterop = new WeakMap();
  33. return (_getRequireWildcardCache = function (nodeInterop) {
  34. return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
  35. })(nodeInterop);
  36. }
  37. function _interopRequireWildcard(obj, nodeInterop) {
  38. if (!nodeInterop && obj && obj.__esModule) {
  39. return obj;
  40. }
  41. if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
  42. return {
  43. default: obj
  44. };
  45. }
  46. var cache = _getRequireWildcardCache(nodeInterop);
  47. if (cache && cache.has(obj)) {
  48. return cache.get(obj);
  49. }
  50. var newObj = {};
  51. var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
  52. for (var key in obj) {
  53. if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
  54. var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
  55. if (desc && (desc.get || desc.set)) {
  56. Object.defineProperty(newObj, key, desc);
  57. } else {
  58. newObj[key] = obj[key];
  59. }
  60. }
  61. }
  62. newObj.default = obj;
  63. if (cache) {
  64. cache.set(obj, newObj);
  65. }
  66. return newObj;
  67. }
  68. var uuidv4 = require('./uuid');
  69. var classMap = {};
  70. var objectCount = 0;
  71. var singleInstance = !_CoreManager.default.get('IS_NODE');
  72. if (singleInstance) {
  73. _CoreManager.default.setObjectStateController(SingleInstanceStateController);
  74. } else {
  75. _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
  76. }
  77. function getServerUrlPath() {
  78. var serverUrl = _CoreManager.default.get('SERVER_URL');
  79. if (serverUrl[serverUrl.length - 1] !== '/') {
  80. serverUrl += '/';
  81. }
  82. var url = serverUrl.replace(/https?:\/\//, '');
  83. return url.substr(url.indexOf('/'));
  84. }
  85. var ParseObject = function () {
  86. function ParseObject(className, attributes, options) {
  87. (0, _classCallCheck2.default)(this, ParseObject);
  88. if (typeof this.initialize === 'function') {
  89. this.initialize.apply(this, arguments);
  90. }
  91. var toSet = null;
  92. this._objCount = objectCount++;
  93. if (typeof className === 'string') {
  94. this.className = className;
  95. if (attributes && typeof attributes === 'object') {
  96. toSet = attributes;
  97. }
  98. } else if (className && typeof className === 'object') {
  99. this.className = className.className;
  100. toSet = {};
  101. for (var _attr in className) {
  102. if (_attr !== 'className') {
  103. toSet[_attr] = className[_attr];
  104. }
  105. }
  106. if (attributes && typeof attributes === 'object') {
  107. options = attributes;
  108. }
  109. }
  110. if (toSet && !this.set(toSet, options)) {
  111. throw new Error("Can't create an invalid Parse Object");
  112. }
  113. }
  114. (0, _createClass2.default)(ParseObject, [{
  115. key: "attributes",
  116. get: function () {
  117. var stateController = _CoreManager.default.getObjectStateController();
  118. return Object.freeze(stateController.estimateAttributes(this._getStateIdentifier()));
  119. }
  120. }, {
  121. key: "createdAt",
  122. get: function () {
  123. return this._getServerData().createdAt;
  124. }
  125. }, {
  126. key: "updatedAt",
  127. get: function () {
  128. return this._getServerData().updatedAt;
  129. }
  130. }, {
  131. key: "_getId",
  132. value: function () {
  133. if (typeof this.id === 'string') {
  134. return this.id;
  135. }
  136. if (typeof this._localId === 'string') {
  137. return this._localId;
  138. }
  139. var localId = 'local' + uuidv4();
  140. this._localId = localId;
  141. return localId;
  142. }
  143. }, {
  144. key: "_getStateIdentifier",
  145. value: function () {
  146. if (singleInstance) {
  147. var id = this.id;
  148. if (!id) {
  149. id = this._getId();
  150. }
  151. return {
  152. id: id,
  153. className: this.className
  154. };
  155. } else {
  156. return this;
  157. }
  158. }
  159. }, {
  160. key: "_getServerData",
  161. value: function () {
  162. var stateController = _CoreManager.default.getObjectStateController();
  163. return stateController.getServerData(this._getStateIdentifier());
  164. }
  165. }, {
  166. key: "_clearServerData",
  167. value: function () {
  168. var serverData = this._getServerData();
  169. var unset = {};
  170. for (var _attr2 in serverData) {
  171. unset[_attr2] = undefined;
  172. }
  173. var stateController = _CoreManager.default.getObjectStateController();
  174. stateController.setServerData(this._getStateIdentifier(), unset);
  175. }
  176. }, {
  177. key: "_getPendingOps",
  178. value: function () {
  179. var stateController = _CoreManager.default.getObjectStateController();
  180. return stateController.getPendingOps(this._getStateIdentifier());
  181. }
  182. }, {
  183. key: "_clearPendingOps",
  184. value: function (keysToClear) {
  185. var pending = this._getPendingOps();
  186. var latest = pending[pending.length - 1];
  187. var keys = keysToClear || Object.keys(latest);
  188. keys.forEach(function (key) {
  189. delete latest[key];
  190. });
  191. }
  192. }, {
  193. key: "_getDirtyObjectAttributes",
  194. value: function () {
  195. var attributes = this.attributes;
  196. var stateController = _CoreManager.default.getObjectStateController();
  197. var objectCache = stateController.getObjectCache(this._getStateIdentifier());
  198. var dirty = {};
  199. for (var _attr3 in attributes) {
  200. var val = attributes[_attr3];
  201. if (val && typeof val === 'object' && !(val instanceof ParseObject) && !(val instanceof _ParseFile.default) && !(val instanceof _ParseRelation.default)) {
  202. try {
  203. var json = (0, _encode.default)(val, false, true);
  204. var stringified = JSON.stringify(json);
  205. if (objectCache[_attr3] !== stringified) {
  206. dirty[_attr3] = val;
  207. }
  208. } catch (e) {
  209. dirty[_attr3] = val;
  210. }
  211. }
  212. }
  213. return dirty;
  214. }
  215. }, {
  216. key: "_toFullJSON",
  217. value: function (seen, offline) {
  218. var json = this.toJSON(seen, offline);
  219. json.__type = 'Object';
  220. json.className = this.className;
  221. return json;
  222. }
  223. }, {
  224. key: "_getSaveJSON",
  225. value: function () {
  226. var pending = this._getPendingOps();
  227. var dirtyObjects = this._getDirtyObjectAttributes();
  228. var json = {};
  229. for (var attr in dirtyObjects) {
  230. var isDotNotation = false;
  231. for (var i = 0; i < pending.length; i += 1) {
  232. for (var field in pending[i]) {
  233. if (field.includes('.')) {
  234. var fieldName = field.split('.')[0];
  235. if (fieldName === attr) {
  236. isDotNotation = true;
  237. break;
  238. }
  239. }
  240. }
  241. }
  242. if (!isDotNotation) {
  243. json[attr] = new _ParseOp.SetOp(dirtyObjects[attr]).toJSON();
  244. }
  245. }
  246. for (attr in pending[0]) {
  247. json[attr] = pending[0][attr].toJSON();
  248. }
  249. return json;
  250. }
  251. }, {
  252. key: "_getSaveParams",
  253. value: function () {
  254. var method = this.id ? 'PUT' : 'POST';
  255. var body = this._getSaveJSON();
  256. var path = 'classes/' + this.className;
  257. if (_CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID')) {
  258. if (!this.createdAt) {
  259. method = 'POST';
  260. body.objectId = this.id;
  261. } else {
  262. method = 'PUT';
  263. path += '/' + this.id;
  264. }
  265. } else if (this.id) {
  266. path += '/' + this.id;
  267. } else if (this.className === '_User') {
  268. path = 'users';
  269. }
  270. return {
  271. method: method,
  272. body: body,
  273. path: path
  274. };
  275. }
  276. }, {
  277. key: "_finishFetch",
  278. value: function (serverData) {
  279. if (!this.id && serverData.objectId) {
  280. this.id = serverData.objectId;
  281. }
  282. var stateController = _CoreManager.default.getObjectStateController();
  283. stateController.initializeState(this._getStateIdentifier());
  284. var decoded = {};
  285. for (var _attr4 in serverData) {
  286. if (_attr4 === 'ACL') {
  287. decoded[_attr4] = new _ParseACL.default(serverData[_attr4]);
  288. } else if (_attr4 !== 'objectId') {
  289. decoded[_attr4] = (0, _decode.default)(serverData[_attr4]);
  290. if (decoded[_attr4] instanceof _ParseRelation.default) {
  291. decoded[_attr4]._ensureParentAndKey(this, _attr4);
  292. }
  293. }
  294. }
  295. if (decoded.createdAt && typeof decoded.createdAt === 'string') {
  296. decoded.createdAt = (0, _parseDate.default)(decoded.createdAt);
  297. }
  298. if (decoded.updatedAt && typeof decoded.updatedAt === 'string') {
  299. decoded.updatedAt = (0, _parseDate.default)(decoded.updatedAt);
  300. }
  301. if (!decoded.updatedAt && decoded.createdAt) {
  302. decoded.updatedAt = decoded.createdAt;
  303. }
  304. stateController.commitServerChanges(this._getStateIdentifier(), decoded);
  305. }
  306. }, {
  307. key: "_setExisted",
  308. value: function (existed) {
  309. var stateController = _CoreManager.default.getObjectStateController();
  310. var state = stateController.getState(this._getStateIdentifier());
  311. if (state) {
  312. state.existed = existed;
  313. }
  314. }
  315. }, {
  316. key: "_migrateId",
  317. value: function (serverId) {
  318. if (this._localId && serverId) {
  319. if (singleInstance) {
  320. var stateController = _CoreManager.default.getObjectStateController();
  321. var oldState = stateController.removeState(this._getStateIdentifier());
  322. this.id = serverId;
  323. delete this._localId;
  324. if (oldState) {
  325. stateController.initializeState(this._getStateIdentifier(), oldState);
  326. }
  327. } else {
  328. this.id = serverId;
  329. delete this._localId;
  330. }
  331. }
  332. }
  333. }, {
  334. key: "_handleSaveResponse",
  335. value: function (response, status) {
  336. var changes = {};
  337. var stateController = _CoreManager.default.getObjectStateController();
  338. var pending = stateController.popPendingState(this._getStateIdentifier());
  339. for (var attr in pending) {
  340. if (pending[attr] instanceof _ParseOp.RelationOp) {
  341. changes[attr] = pending[attr].applyTo(undefined, this, attr);
  342. } else if (!(attr in response)) {
  343. changes[attr] = pending[attr].applyTo(undefined);
  344. }
  345. }
  346. for (attr in response) {
  347. if ((attr === 'createdAt' || attr === 'updatedAt') && typeof response[attr] === 'string') {
  348. changes[attr] = (0, _parseDate.default)(response[attr]);
  349. } else if (attr === 'ACL') {
  350. changes[attr] = new _ParseACL.default(response[attr]);
  351. } else if (attr !== 'objectId') {
  352. var val = (0, _decode.default)(response[attr]);
  353. if (val && Object.getPrototypeOf(val) === Object.prototype) {
  354. changes[attr] = Object.assign({}, this.attributes[attr], val);
  355. } else {
  356. changes[attr] = val;
  357. }
  358. if (changes[attr] instanceof _ParseOp.UnsetOp) {
  359. changes[attr] = undefined;
  360. }
  361. }
  362. }
  363. if (changes.createdAt && !changes.updatedAt) {
  364. changes.updatedAt = changes.createdAt;
  365. }
  366. this._migrateId(response.objectId);
  367. if (status !== 201) {
  368. this._setExisted(true);
  369. }
  370. stateController.commitServerChanges(this._getStateIdentifier(), changes);
  371. }
  372. }, {
  373. key: "_handleSaveError",
  374. value: function () {
  375. var stateController = _CoreManager.default.getObjectStateController();
  376. stateController.mergeFirstPendingState(this._getStateIdentifier());
  377. }
  378. }, {
  379. key: "initialize",
  380. value: function () {}
  381. }, {
  382. key: "toJSON",
  383. value: function (seen, offline) {
  384. var seenEntry = this.id ? this.className + ':' + this.id : this;
  385. seen = seen || [seenEntry];
  386. var json = {};
  387. var attrs = this.attributes;
  388. for (var _attr5 in attrs) {
  389. if ((_attr5 === 'createdAt' || _attr5 === 'updatedAt') && attrs[_attr5].toJSON) {
  390. json[_attr5] = attrs[_attr5].toJSON();
  391. } else {
  392. json[_attr5] = (0, _encode.default)(attrs[_attr5], false, false, seen, offline);
  393. }
  394. }
  395. var pending = this._getPendingOps();
  396. for (var _attr6 in pending[0]) {
  397. json[_attr6] = pending[0][_attr6].toJSON(offline);
  398. }
  399. if (this.id) {
  400. json.objectId = this.id;
  401. }
  402. return json;
  403. }
  404. }, {
  405. key: "equals",
  406. value: function (other) {
  407. if (this === other) {
  408. return true;
  409. }
  410. return other instanceof ParseObject && this.className === other.className && this.id === other.id && typeof this.id !== 'undefined';
  411. }
  412. }, {
  413. key: "dirty",
  414. value: function (attr) {
  415. if (!this.id) {
  416. return true;
  417. }
  418. var pendingOps = this._getPendingOps();
  419. var dirtyObjects = this._getDirtyObjectAttributes();
  420. if (attr) {
  421. if (dirtyObjects.hasOwnProperty(attr)) {
  422. return true;
  423. }
  424. for (var i = 0; i < pendingOps.length; i++) {
  425. if (pendingOps[i].hasOwnProperty(attr)) {
  426. return true;
  427. }
  428. }
  429. return false;
  430. }
  431. if (Object.keys(pendingOps[0]).length !== 0) {
  432. return true;
  433. }
  434. if (Object.keys(dirtyObjects).length !== 0) {
  435. return true;
  436. }
  437. return false;
  438. }
  439. }, {
  440. key: "dirtyKeys",
  441. value: function () {
  442. var pendingOps = this._getPendingOps();
  443. var keys = {};
  444. for (var i = 0; i < pendingOps.length; i++) {
  445. for (var _attr7 in pendingOps[i]) {
  446. keys[_attr7] = true;
  447. }
  448. }
  449. var dirtyObjects = this._getDirtyObjectAttributes();
  450. for (var _attr8 in dirtyObjects) {
  451. keys[_attr8] = true;
  452. }
  453. return Object.keys(keys);
  454. }
  455. }, {
  456. key: "isDataAvailable",
  457. value: function () {
  458. var serverData = this._getServerData();
  459. return !!Object.keys(serverData).length;
  460. }
  461. }, {
  462. key: "toPointer",
  463. value: function () {
  464. if (!this.id) {
  465. throw new Error('Cannot create a pointer to an unsaved ParseObject');
  466. }
  467. return {
  468. __type: 'Pointer',
  469. className: this.className,
  470. objectId: this.id
  471. };
  472. }
  473. }, {
  474. key: "toOfflinePointer",
  475. value: function () {
  476. if (!this._localId) {
  477. throw new Error('Cannot create a offline pointer to a saved ParseObject');
  478. }
  479. return {
  480. __type: 'Object',
  481. className: this.className,
  482. _localId: this._localId
  483. };
  484. }
  485. }, {
  486. key: "get",
  487. value: function (attr) {
  488. return this.attributes[attr];
  489. }
  490. }, {
  491. key: "relation",
  492. value: function (attr) {
  493. var value = this.get(attr);
  494. if (value) {
  495. if (!(value instanceof _ParseRelation.default)) {
  496. throw new Error('Called relation() on non-relation field ' + attr);
  497. }
  498. value._ensureParentAndKey(this, attr);
  499. return value;
  500. }
  501. return new _ParseRelation.default(this, attr);
  502. }
  503. }, {
  504. key: "escape",
  505. value: function (attr) {
  506. var val = this.attributes[attr];
  507. if (val == null) {
  508. return '';
  509. }
  510. if (typeof val !== 'string') {
  511. if (typeof val.toString !== 'function') {
  512. return '';
  513. }
  514. val = val.toString();
  515. }
  516. return (0, _escape2.default)(val);
  517. }
  518. }, {
  519. key: "has",
  520. value: function (attr) {
  521. var attributes = this.attributes;
  522. if (attributes.hasOwnProperty(attr)) {
  523. return attributes[attr] != null;
  524. }
  525. return false;
  526. }
  527. }, {
  528. key: "set",
  529. value: function (key, value, options) {
  530. var changes = {};
  531. var newOps = {};
  532. if (key && typeof key === 'object') {
  533. changes = key;
  534. options = value;
  535. } else if (typeof key === 'string') {
  536. changes[key] = value;
  537. } else {
  538. return this;
  539. }
  540. options = options || {};
  541. var readonly = [];
  542. if (typeof this.constructor.readOnlyAttributes === 'function') {
  543. readonly = readonly.concat(this.constructor.readOnlyAttributes());
  544. }
  545. for (var k in changes) {
  546. if (k === 'createdAt' || k === 'updatedAt') {
  547. continue;
  548. }
  549. if (readonly.indexOf(k) > -1) {
  550. throw new Error('Cannot modify readonly attribute: ' + k);
  551. }
  552. if (options.unset) {
  553. newOps[k] = new _ParseOp.UnsetOp();
  554. } else if (changes[k] instanceof _ParseOp.Op) {
  555. newOps[k] = changes[k];
  556. } else if (changes[k] && typeof changes[k] === 'object' && typeof changes[k].__op === 'string') {
  557. newOps[k] = (0, _ParseOp.opFromJSON)(changes[k]);
  558. } else if (k === 'objectId' || k === 'id') {
  559. if (typeof changes[k] === 'string') {
  560. this.id = changes[k];
  561. }
  562. } else if (k === 'ACL' && typeof changes[k] === 'object' && !(changes[k] instanceof _ParseACL.default)) {
  563. newOps[k] = new _ParseOp.SetOp(new _ParseACL.default(changes[k]));
  564. } else if (changes[k] instanceof _ParseRelation.default) {
  565. var relation = new _ParseRelation.default(this, k);
  566. relation.targetClassName = changes[k].targetClassName;
  567. newOps[k] = new _ParseOp.SetOp(relation);
  568. } else {
  569. newOps[k] = new _ParseOp.SetOp(changes[k]);
  570. }
  571. }
  572. var currentAttributes = this.attributes;
  573. var newValues = {};
  574. for (var _attr9 in newOps) {
  575. if (newOps[_attr9] instanceof _ParseOp.RelationOp) {
  576. newValues[_attr9] = newOps[_attr9].applyTo(currentAttributes[_attr9], this, _attr9);
  577. } else if (!(newOps[_attr9] instanceof _ParseOp.UnsetOp)) {
  578. newValues[_attr9] = newOps[_attr9].applyTo(currentAttributes[_attr9]);
  579. }
  580. }
  581. if (!options.ignoreValidation) {
  582. var validation = this.validate(newValues);
  583. if (validation) {
  584. if (typeof options.error === 'function') {
  585. options.error(this, validation);
  586. }
  587. return false;
  588. }
  589. }
  590. var pendingOps = this._getPendingOps();
  591. var last = pendingOps.length - 1;
  592. var stateController = _CoreManager.default.getObjectStateController();
  593. for (var _attr10 in newOps) {
  594. var nextOp = newOps[_attr10].mergeWith(pendingOps[last][_attr10]);
  595. stateController.setPendingOp(this._getStateIdentifier(), _attr10, nextOp);
  596. }
  597. return this;
  598. }
  599. }, {
  600. key: "unset",
  601. value: function (attr, options) {
  602. options = options || {};
  603. options.unset = true;
  604. return this.set(attr, null, options);
  605. }
  606. }, {
  607. key: "increment",
  608. value: function (attr, amount) {
  609. if (typeof amount === 'undefined') {
  610. amount = 1;
  611. }
  612. if (typeof amount !== 'number') {
  613. throw new Error('Cannot increment by a non-numeric amount.');
  614. }
  615. return this.set(attr, new _ParseOp.IncrementOp(amount));
  616. }
  617. }, {
  618. key: "decrement",
  619. value: function (attr, amount) {
  620. if (typeof amount === 'undefined') {
  621. amount = 1;
  622. }
  623. if (typeof amount !== 'number') {
  624. throw new Error('Cannot decrement by a non-numeric amount.');
  625. }
  626. return this.set(attr, new _ParseOp.IncrementOp(amount * -1));
  627. }
  628. }, {
  629. key: "add",
  630. value: function (attr, item) {
  631. return this.set(attr, new _ParseOp.AddOp([item]));
  632. }
  633. }, {
  634. key: "addAll",
  635. value: function (attr, items) {
  636. return this.set(attr, new _ParseOp.AddOp(items));
  637. }
  638. }, {
  639. key: "addUnique",
  640. value: function (attr, item) {
  641. return this.set(attr, new _ParseOp.AddUniqueOp([item]));
  642. }
  643. }, {
  644. key: "addAllUnique",
  645. value: function (attr, items) {
  646. return this.set(attr, new _ParseOp.AddUniqueOp(items));
  647. }
  648. }, {
  649. key: "remove",
  650. value: function (attr, item) {
  651. return this.set(attr, new _ParseOp.RemoveOp([item]));
  652. }
  653. }, {
  654. key: "removeAll",
  655. value: function (attr, items) {
  656. return this.set(attr, new _ParseOp.RemoveOp(items));
  657. }
  658. }, {
  659. key: "op",
  660. value: function (attr) {
  661. var pending = this._getPendingOps();
  662. for (var i = pending.length; i--;) {
  663. if (pending[i][attr]) {
  664. return pending[i][attr];
  665. }
  666. }
  667. }
  668. }, {
  669. key: "clone",
  670. value: function clone() {
  671. var clone = new this.constructor(this.className);
  672. var attributes = this.attributes;
  673. if (typeof this.constructor.readOnlyAttributes === 'function') {
  674. var readonly = this.constructor.readOnlyAttributes() || [];
  675. var copy = {};
  676. for (var a in attributes) {
  677. if (readonly.indexOf(a) < 0) {
  678. copy[a] = attributes[a];
  679. }
  680. }
  681. attributes = copy;
  682. }
  683. if (clone.set) {
  684. clone.set(attributes);
  685. }
  686. return clone;
  687. }
  688. }, {
  689. key: "newInstance",
  690. value: function () {
  691. var clone = new this.constructor(this.className);
  692. clone.id = this.id;
  693. if (singleInstance) {
  694. return clone;
  695. }
  696. var stateController = _CoreManager.default.getObjectStateController();
  697. if (stateController) {
  698. stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier());
  699. }
  700. return clone;
  701. }
  702. }, {
  703. key: "isNew",
  704. value: function () {
  705. return !this.id;
  706. }
  707. }, {
  708. key: "existed",
  709. value: function () {
  710. if (!this.id) {
  711. return false;
  712. }
  713. var stateController = _CoreManager.default.getObjectStateController();
  714. var state = stateController.getState(this._getStateIdentifier());
  715. if (state) {
  716. return state.existed;
  717. }
  718. return false;
  719. }
  720. }, {
  721. key: "exists",
  722. value: function () {
  723. var _exists = (0, _asyncToGenerator2.default)(function* (options) {
  724. if (!this.id) {
  725. return false;
  726. }
  727. try {
  728. var query = new _ParseQuery.default(this.className);
  729. yield query.get(this.id, options);
  730. return true;
  731. } catch (e) {
  732. if (e.code === _ParseError.default.OBJECT_NOT_FOUND) {
  733. return false;
  734. }
  735. throw e;
  736. }
  737. });
  738. function exists() {
  739. return _exists.apply(this, arguments);
  740. }
  741. return exists;
  742. }()
  743. }, {
  744. key: "isValid",
  745. value: function () {
  746. return !this.validate(this.attributes);
  747. }
  748. }, {
  749. key: "validate",
  750. value: function (attrs) {
  751. if (attrs.hasOwnProperty('ACL') && !(attrs.ACL instanceof _ParseACL.default)) {
  752. return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'ACL must be a Parse ACL.');
  753. }
  754. for (var _key in attrs) {
  755. if (!/^[A-Za-z][0-9A-Za-z_.]*$/.test(_key)) {
  756. return new _ParseError.default(_ParseError.default.INVALID_KEY_NAME);
  757. }
  758. }
  759. return false;
  760. }
  761. }, {
  762. key: "getACL",
  763. value: function () {
  764. var acl = this.get('ACL');
  765. if (acl instanceof _ParseACL.default) {
  766. return acl;
  767. }
  768. return null;
  769. }
  770. }, {
  771. key: "setACL",
  772. value: function (acl, options) {
  773. return this.set('ACL', acl, options);
  774. }
  775. }, {
  776. key: "revert",
  777. value: function () {
  778. var keysToRevert;
  779. for (var _len = arguments.length, keys = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
  780. keys[_key2] = arguments[_key2];
  781. }
  782. if (keys.length) {
  783. keysToRevert = [];
  784. for (var _key3 of keys) {
  785. if (typeof _key3 === 'string') {
  786. keysToRevert.push(_key3);
  787. } else {
  788. throw new Error('Parse.Object#revert expects either no, or a list of string, arguments.');
  789. }
  790. }
  791. }
  792. this._clearPendingOps(keysToRevert);
  793. }
  794. }, {
  795. key: "clear",
  796. value: function () {
  797. var attributes = this.attributes;
  798. var erasable = {};
  799. var readonly = ['createdAt', 'updatedAt'];
  800. if (typeof this.constructor.readOnlyAttributes === 'function') {
  801. readonly = readonly.concat(this.constructor.readOnlyAttributes());
  802. }
  803. for (var _attr11 in attributes) {
  804. if (readonly.indexOf(_attr11) < 0) {
  805. erasable[_attr11] = true;
  806. }
  807. }
  808. return this.set(erasable, {
  809. unset: true
  810. });
  811. }
  812. }, {
  813. key: "fetch",
  814. value: function (options) {
  815. options = options || {};
  816. var fetchOptions = {};
  817. if (options.hasOwnProperty('useMasterKey')) {
  818. fetchOptions.useMasterKey = options.useMasterKey;
  819. }
  820. if (options.hasOwnProperty('sessionToken')) {
  821. fetchOptions.sessionToken = options.sessionToken;
  822. }
  823. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  824. fetchOptions.context = options.context;
  825. }
  826. if (options.hasOwnProperty('include')) {
  827. fetchOptions.include = [];
  828. if (Array.isArray(options.include)) {
  829. options.include.forEach(function (key) {
  830. if (Array.isArray(key)) {
  831. fetchOptions.include = fetchOptions.include.concat(key);
  832. } else {
  833. fetchOptions.include.push(key);
  834. }
  835. });
  836. } else {
  837. fetchOptions.include.push(options.include);
  838. }
  839. }
  840. var controller = _CoreManager.default.getObjectController();
  841. return controller.fetch(this, true, fetchOptions);
  842. }
  843. }, {
  844. key: "fetchWithInclude",
  845. value: function (keys, options) {
  846. options = options || {};
  847. options.include = keys;
  848. return this.fetch(options);
  849. }
  850. }, {
  851. key: "saveEventually",
  852. value: function () {
  853. var _saveEventually = (0, _asyncToGenerator2.default)(function* (options) {
  854. try {
  855. yield this.save(null, options);
  856. } catch (e) {
  857. if (e.message === 'XMLHttpRequest failed: "Unable to connect to the Parse API"') {
  858. yield _EventuallyQueue.default.save(this, options);
  859. _EventuallyQueue.default.poll();
  860. }
  861. }
  862. return this;
  863. });
  864. function saveEventually() {
  865. return _saveEventually.apply(this, arguments);
  866. }
  867. return saveEventually;
  868. }()
  869. }, {
  870. key: "save",
  871. value: function (arg1, arg2, arg3) {
  872. var _this = this;
  873. var attrs;
  874. var options;
  875. if (typeof arg1 === 'object' || typeof arg1 === 'undefined') {
  876. attrs = arg1;
  877. if (typeof arg2 === 'object') {
  878. options = arg2;
  879. }
  880. } else {
  881. attrs = {};
  882. attrs[arg1] = arg2;
  883. options = arg3;
  884. }
  885. if (attrs) {
  886. var validation = this.validate(attrs);
  887. if (validation) {
  888. return Promise.reject(validation);
  889. }
  890. this.set(attrs, options);
  891. }
  892. options = options || {};
  893. var saveOptions = {};
  894. if (options.hasOwnProperty('useMasterKey')) {
  895. saveOptions.useMasterKey = !!options.useMasterKey;
  896. }
  897. if (options.hasOwnProperty('sessionToken') && typeof options.sessionToken === 'string') {
  898. saveOptions.sessionToken = options.sessionToken;
  899. }
  900. if (options.hasOwnProperty('installationId') && typeof options.installationId === 'string') {
  901. saveOptions.installationId = options.installationId;
  902. }
  903. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  904. saveOptions.context = options.context;
  905. }
  906. var controller = _CoreManager.default.getObjectController();
  907. var unsaved = options.cascadeSave !== false ? (0, _unsavedChildren.default)(this) : null;
  908. return controller.save(unsaved, saveOptions).then(function () {
  909. return controller.save(_this, saveOptions);
  910. });
  911. }
  912. }, {
  913. key: "destroyEventually",
  914. value: function () {
  915. var _destroyEventually = (0, _asyncToGenerator2.default)(function* (options) {
  916. try {
  917. yield this.destroy(options);
  918. } catch (e) {
  919. if (e.message === 'XMLHttpRequest failed: "Unable to connect to the Parse API"') {
  920. yield _EventuallyQueue.default.destroy(this, options);
  921. _EventuallyQueue.default.poll();
  922. }
  923. }
  924. return this;
  925. });
  926. function destroyEventually() {
  927. return _destroyEventually.apply(this, arguments);
  928. }
  929. return destroyEventually;
  930. }()
  931. }, {
  932. key: "destroy",
  933. value: function (options) {
  934. options = options || {};
  935. var destroyOptions = {};
  936. if (options.hasOwnProperty('useMasterKey')) {
  937. destroyOptions.useMasterKey = options.useMasterKey;
  938. }
  939. if (options.hasOwnProperty('sessionToken')) {
  940. destroyOptions.sessionToken = options.sessionToken;
  941. }
  942. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  943. destroyOptions.context = options.context;
  944. }
  945. if (!this.id) {
  946. return Promise.resolve();
  947. }
  948. return _CoreManager.default.getObjectController().destroy(this, destroyOptions);
  949. }
  950. }, {
  951. key: "pin",
  952. value: function () {
  953. return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
  954. }
  955. }, {
  956. key: "unPin",
  957. value: function () {
  958. return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
  959. }
  960. }, {
  961. key: "isPinned",
  962. value: function () {
  963. var _isPinned = (0, _asyncToGenerator2.default)(function* () {
  964. var localDatastore = _CoreManager.default.getLocalDatastore();
  965. if (!localDatastore.isEnabled) {
  966. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  967. }
  968. var objectKey = localDatastore.getKeyForObject(this);
  969. var pin = yield localDatastore.fromPinWithName(objectKey);
  970. return pin.length > 0;
  971. });
  972. function isPinned() {
  973. return _isPinned.apply(this, arguments);
  974. }
  975. return isPinned;
  976. }()
  977. }, {
  978. key: "pinWithName",
  979. value: function (name) {
  980. return ParseObject.pinAllWithName(name, [this]);
  981. }
  982. }, {
  983. key: "unPinWithName",
  984. value: function (name) {
  985. return ParseObject.unPinAllWithName(name, [this]);
  986. }
  987. }, {
  988. key: "fetchFromLocalDatastore",
  989. value: function () {
  990. var _fetchFromLocalDatastore = (0, _asyncToGenerator2.default)(function* () {
  991. var localDatastore = _CoreManager.default.getLocalDatastore();
  992. if (!localDatastore.isEnabled) {
  993. throw new Error('Parse.enableLocalDatastore() must be called first');
  994. }
  995. var objectKey = localDatastore.getKeyForObject(this);
  996. var pinned = yield localDatastore._serializeObject(objectKey);
  997. if (!pinned) {
  998. throw new Error('Cannot fetch an unsaved ParseObject');
  999. }
  1000. var result = ParseObject.fromJSON(pinned);
  1001. this._finishFetch(result.toJSON());
  1002. return this;
  1003. });
  1004. function fetchFromLocalDatastore() {
  1005. return _fetchFromLocalDatastore.apply(this, arguments);
  1006. }
  1007. return fetchFromLocalDatastore;
  1008. }()
  1009. }], [{
  1010. key: "_getClassMap",
  1011. value: function () {
  1012. return classMap;
  1013. }
  1014. }, {
  1015. key: "_clearAllState",
  1016. value: function () {
  1017. var stateController = _CoreManager.default.getObjectStateController();
  1018. stateController.clearAllState();
  1019. }
  1020. }, {
  1021. key: "fetchAll",
  1022. value: function (list) {
  1023. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1024. var queryOptions = {};
  1025. if (options.hasOwnProperty('useMasterKey')) {
  1026. queryOptions.useMasterKey = options.useMasterKey;
  1027. }
  1028. if (options.hasOwnProperty('sessionToken')) {
  1029. queryOptions.sessionToken = options.sessionToken;
  1030. }
  1031. if (options.hasOwnProperty('include')) {
  1032. queryOptions.include = ParseObject.handleIncludeOptions(options);
  1033. }
  1034. return _CoreManager.default.getObjectController().fetch(list, true, queryOptions);
  1035. }
  1036. }, {
  1037. key: "fetchAllWithInclude",
  1038. value: function (list, keys, options) {
  1039. options = options || {};
  1040. options.include = keys;
  1041. return ParseObject.fetchAll(list, options);
  1042. }
  1043. }, {
  1044. key: "fetchAllIfNeededWithInclude",
  1045. value: function (list, keys, options) {
  1046. options = options || {};
  1047. options.include = keys;
  1048. return ParseObject.fetchAllIfNeeded(list, options);
  1049. }
  1050. }, {
  1051. key: "fetchAllIfNeeded",
  1052. value: function (list, options) {
  1053. options = options || {};
  1054. var queryOptions = {};
  1055. if (options.hasOwnProperty('useMasterKey')) {
  1056. queryOptions.useMasterKey = options.useMasterKey;
  1057. }
  1058. if (options.hasOwnProperty('sessionToken')) {
  1059. queryOptions.sessionToken = options.sessionToken;
  1060. }
  1061. if (options.hasOwnProperty('include')) {
  1062. queryOptions.include = ParseObject.handleIncludeOptions(options);
  1063. }
  1064. return _CoreManager.default.getObjectController().fetch(list, false, queryOptions);
  1065. }
  1066. }, {
  1067. key: "handleIncludeOptions",
  1068. value: function (options) {
  1069. var include = [];
  1070. if (Array.isArray(options.include)) {
  1071. options.include.forEach(function (key) {
  1072. if (Array.isArray(key)) {
  1073. include = include.concat(key);
  1074. } else {
  1075. include.push(key);
  1076. }
  1077. });
  1078. } else {
  1079. include.push(options.include);
  1080. }
  1081. return include;
  1082. }
  1083. }, {
  1084. key: "destroyAll",
  1085. value: function (list) {
  1086. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1087. var destroyOptions = {};
  1088. if (options.hasOwnProperty('useMasterKey')) {
  1089. destroyOptions.useMasterKey = options.useMasterKey;
  1090. }
  1091. if (options.hasOwnProperty('sessionToken')) {
  1092. destroyOptions.sessionToken = options.sessionToken;
  1093. }
  1094. if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
  1095. destroyOptions.batchSize = options.batchSize;
  1096. }
  1097. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  1098. destroyOptions.context = options.context;
  1099. }
  1100. return _CoreManager.default.getObjectController().destroy(list, destroyOptions);
  1101. }
  1102. }, {
  1103. key: "saveAll",
  1104. value: function (list) {
  1105. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1106. var saveOptions = {};
  1107. if (options.hasOwnProperty('useMasterKey')) {
  1108. saveOptions.useMasterKey = options.useMasterKey;
  1109. }
  1110. if (options.hasOwnProperty('sessionToken')) {
  1111. saveOptions.sessionToken = options.sessionToken;
  1112. }
  1113. if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
  1114. saveOptions.batchSize = options.batchSize;
  1115. }
  1116. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  1117. saveOptions.context = options.context;
  1118. }
  1119. return _CoreManager.default.getObjectController().save(list, saveOptions);
  1120. }
  1121. }, {
  1122. key: "createWithoutData",
  1123. value: function (id) {
  1124. var obj = new this();
  1125. obj.id = id;
  1126. return obj;
  1127. }
  1128. }, {
  1129. key: "fromJSON",
  1130. value: function (json, override, dirty) {
  1131. if (!json.className) {
  1132. throw new Error('Cannot create an object without a className');
  1133. }
  1134. var constructor = classMap[json.className];
  1135. var o = constructor ? new constructor(json.className) : new ParseObject(json.className);
  1136. var otherAttributes = {};
  1137. for (var _attr12 in json) {
  1138. if (_attr12 !== 'className' && _attr12 !== '__type') {
  1139. otherAttributes[_attr12] = json[_attr12];
  1140. if (dirty) {
  1141. o.set(_attr12, json[_attr12]);
  1142. }
  1143. }
  1144. }
  1145. if (override) {
  1146. if (otherAttributes.objectId) {
  1147. o.id = otherAttributes.objectId;
  1148. }
  1149. var preserved = null;
  1150. if (typeof o._preserveFieldsOnFetch === 'function') {
  1151. preserved = o._preserveFieldsOnFetch();
  1152. }
  1153. o._clearServerData();
  1154. if (preserved) {
  1155. o._finishFetch(preserved);
  1156. }
  1157. }
  1158. o._finishFetch(otherAttributes);
  1159. if (json.objectId) {
  1160. o._setExisted(true);
  1161. }
  1162. return o;
  1163. }
  1164. }, {
  1165. key: "registerSubclass",
  1166. value: function (className, constructor) {
  1167. if (typeof className !== 'string') {
  1168. throw new TypeError('The first argument must be a valid class name.');
  1169. }
  1170. if (typeof constructor === 'undefined') {
  1171. throw new TypeError('You must supply a subclass constructor.');
  1172. }
  1173. if (typeof constructor !== 'function') {
  1174. throw new TypeError('You must register the subclass constructor. ' + 'Did you attempt to register an instance of the subclass?');
  1175. }
  1176. classMap[className] = constructor;
  1177. if (!constructor.className) {
  1178. constructor.className = className;
  1179. }
  1180. }
  1181. }, {
  1182. key: "unregisterSubclass",
  1183. value: function (className) {
  1184. if (typeof className !== 'string') {
  1185. throw new TypeError('The first argument must be a valid class name.');
  1186. }
  1187. delete classMap[className];
  1188. }
  1189. }, {
  1190. key: "extend",
  1191. value: function (className, protoProps, classProps) {
  1192. if (typeof className !== 'string') {
  1193. if (className && typeof className.className === 'string') {
  1194. return ParseObject.extend(className.className, className, protoProps);
  1195. } else {
  1196. throw new Error("Parse.Object.extend's first argument should be the className.");
  1197. }
  1198. }
  1199. var adjustedClassName = className;
  1200. if (adjustedClassName === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
  1201. adjustedClassName = '_User';
  1202. }
  1203. var parentProto = ParseObject.prototype;
  1204. if (this.hasOwnProperty('__super__') && this.__super__) {
  1205. parentProto = this.prototype;
  1206. }
  1207. var ParseObjectSubclass = function (attributes, options) {
  1208. this.className = adjustedClassName;
  1209. this._objCount = objectCount++;
  1210. if (typeof this.initialize === 'function') {
  1211. this.initialize.apply(this, arguments);
  1212. }
  1213. if (this._initializers) {
  1214. for (var initializer of this._initializers) {
  1215. initializer.apply(this, arguments);
  1216. }
  1217. }
  1218. if (attributes && typeof attributes === 'object') {
  1219. if (!this.set(attributes || {}, options)) {
  1220. throw new Error("Can't create an invalid Parse Object");
  1221. }
  1222. }
  1223. };
  1224. if (classMap[adjustedClassName]) {
  1225. ParseObjectSubclass = classMap[adjustedClassName];
  1226. } else {
  1227. ParseObjectSubclass.extend = function (name, protoProps, classProps) {
  1228. if (typeof name === 'string') {
  1229. return ParseObject.extend.call(ParseObjectSubclass, name, protoProps, classProps);
  1230. }
  1231. return ParseObject.extend.call(ParseObjectSubclass, adjustedClassName, name, protoProps);
  1232. };
  1233. ParseObjectSubclass.createWithoutData = ParseObject.createWithoutData;
  1234. ParseObjectSubclass.className = adjustedClassName;
  1235. ParseObjectSubclass.__super__ = parentProto;
  1236. ParseObjectSubclass.prototype = Object.create(parentProto, {
  1237. constructor: {
  1238. value: ParseObjectSubclass,
  1239. enumerable: false,
  1240. writable: true,
  1241. configurable: true
  1242. }
  1243. });
  1244. }
  1245. if (protoProps) {
  1246. for (var prop in protoProps) {
  1247. if (prop === 'initialize') {
  1248. Object.defineProperty(ParseObjectSubclass.prototype, '_initializers', {
  1249. value: [].concat((0, _toConsumableArray2.default)(ParseObjectSubclass.prototype._initializers || []), [protoProps[prop]]),
  1250. enumerable: false,
  1251. writable: true,
  1252. configurable: true
  1253. });
  1254. continue;
  1255. }
  1256. if (prop !== 'className') {
  1257. Object.defineProperty(ParseObjectSubclass.prototype, prop, {
  1258. value: protoProps[prop],
  1259. enumerable: false,
  1260. writable: true,
  1261. configurable: true
  1262. });
  1263. }
  1264. }
  1265. }
  1266. if (classProps) {
  1267. for (var _prop in classProps) {
  1268. if (_prop !== 'className') {
  1269. Object.defineProperty(ParseObjectSubclass, _prop, {
  1270. value: classProps[_prop],
  1271. enumerable: false,
  1272. writable: true,
  1273. configurable: true
  1274. });
  1275. }
  1276. }
  1277. }
  1278. classMap[adjustedClassName] = ParseObjectSubclass;
  1279. return ParseObjectSubclass;
  1280. }
  1281. }, {
  1282. key: "enableSingleInstance",
  1283. value: function () {
  1284. singleInstance = true;
  1285. _CoreManager.default.setObjectStateController(SingleInstanceStateController);
  1286. }
  1287. }, {
  1288. key: "disableSingleInstance",
  1289. value: function () {
  1290. singleInstance = false;
  1291. _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
  1292. }
  1293. }, {
  1294. key: "pinAll",
  1295. value: function (objects) {
  1296. var localDatastore = _CoreManager.default.getLocalDatastore();
  1297. if (!localDatastore.isEnabled) {
  1298. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  1299. }
  1300. return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
  1301. }
  1302. }, {
  1303. key: "pinAllWithName",
  1304. value: function (name, objects) {
  1305. var localDatastore = _CoreManager.default.getLocalDatastore();
  1306. if (!localDatastore.isEnabled) {
  1307. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  1308. }
  1309. return localDatastore._handlePinAllWithName(name, objects);
  1310. }
  1311. }, {
  1312. key: "unPinAll",
  1313. value: function (objects) {
  1314. var localDatastore = _CoreManager.default.getLocalDatastore();
  1315. if (!localDatastore.isEnabled) {
  1316. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  1317. }
  1318. return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
  1319. }
  1320. }, {
  1321. key: "unPinAllWithName",
  1322. value: function (name, objects) {
  1323. var localDatastore = _CoreManager.default.getLocalDatastore();
  1324. if (!localDatastore.isEnabled) {
  1325. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  1326. }
  1327. return localDatastore._handleUnPinAllWithName(name, objects);
  1328. }
  1329. }, {
  1330. key: "unPinAllObjects",
  1331. value: function () {
  1332. var localDatastore = _CoreManager.default.getLocalDatastore();
  1333. if (!localDatastore.isEnabled) {
  1334. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  1335. }
  1336. return localDatastore.unPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
  1337. }
  1338. }, {
  1339. key: "unPinAllObjectsWithName",
  1340. value: function (name) {
  1341. var localDatastore = _CoreManager.default.getLocalDatastore();
  1342. if (!localDatastore.isEnabled) {
  1343. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  1344. }
  1345. return localDatastore.unPinWithName(_LocalDatastoreUtils.PIN_PREFIX + name);
  1346. }
  1347. }]);
  1348. return ParseObject;
  1349. }();
  1350. var DefaultController = {
  1351. fetch: function (target, forceFetch, options) {
  1352. var localDatastore = _CoreManager.default.getLocalDatastore();
  1353. if (Array.isArray(target)) {
  1354. if (target.length < 1) {
  1355. return Promise.resolve([]);
  1356. }
  1357. var objs = [];
  1358. var ids = [];
  1359. var className = null;
  1360. var results = [];
  1361. var error = null;
  1362. target.forEach(function (el) {
  1363. if (error) {
  1364. return;
  1365. }
  1366. if (!className) {
  1367. className = el.className;
  1368. }
  1369. if (className !== el.className) {
  1370. error = new _ParseError.default(_ParseError.default.INVALID_CLASS_NAME, 'All objects should be of the same class');
  1371. }
  1372. if (!el.id) {
  1373. error = new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'All objects must have an ID');
  1374. }
  1375. if (forceFetch || !el.isDataAvailable()) {
  1376. ids.push(el.id);
  1377. objs.push(el);
  1378. }
  1379. results.push(el);
  1380. });
  1381. if (error) {
  1382. return Promise.reject(error);
  1383. }
  1384. var query = new _ParseQuery.default(className);
  1385. query.containedIn('objectId', ids);
  1386. if (options && options.include) {
  1387. query.include(options.include);
  1388. }
  1389. query._limit = ids.length;
  1390. return query.find(options).then(function () {
  1391. var _ref = (0, _asyncToGenerator2.default)(function* (objects) {
  1392. var idMap = {};
  1393. objects.forEach(function (o) {
  1394. idMap[o.id] = o;
  1395. });
  1396. for (var i = 0; i < objs.length; i++) {
  1397. var obj = objs[i];
  1398. if (!obj || !obj.id || !idMap[obj.id]) {
  1399. if (forceFetch) {
  1400. return Promise.reject(new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'All objects must exist on the server.'));
  1401. }
  1402. }
  1403. }
  1404. if (!singleInstance) {
  1405. for (var _i = 0; _i < results.length; _i++) {
  1406. var _obj = results[_i];
  1407. if (_obj && _obj.id && idMap[_obj.id]) {
  1408. var id = _obj.id;
  1409. _obj._finishFetch(idMap[id].toJSON());
  1410. results[_i] = idMap[id];
  1411. }
  1412. }
  1413. }
  1414. for (var object of results) {
  1415. yield localDatastore._updateObjectIfPinned(object);
  1416. }
  1417. return Promise.resolve(results);
  1418. });
  1419. return function () {
  1420. return _ref.apply(this, arguments);
  1421. };
  1422. }());
  1423. } else if (target instanceof ParseObject) {
  1424. if (!target.id) {
  1425. return Promise.reject(new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'Object does not have an ID'));
  1426. }
  1427. var RESTController = _CoreManager.default.getRESTController();
  1428. var params = {};
  1429. if (options && options.include) {
  1430. params.include = options.include.join();
  1431. }
  1432. return RESTController.request('GET', 'classes/' + target.className + '/' + target._getId(), params, options).then(function () {
  1433. var _ref2 = (0, _asyncToGenerator2.default)(function* (response) {
  1434. target._clearPendingOps();
  1435. target._clearServerData();
  1436. target._finishFetch(response);
  1437. yield localDatastore._updateObjectIfPinned(target);
  1438. return target;
  1439. });
  1440. return function () {
  1441. return _ref2.apply(this, arguments);
  1442. };
  1443. }());
  1444. }
  1445. return Promise.resolve();
  1446. },
  1447. destroy: function () {
  1448. var _destroy = (0, _asyncToGenerator2.default)(function* (target, options) {
  1449. var batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
  1450. var localDatastore = _CoreManager.default.getLocalDatastore();
  1451. var RESTController = _CoreManager.default.getRESTController();
  1452. if (Array.isArray(target)) {
  1453. if (target.length < 1) {
  1454. return Promise.resolve([]);
  1455. }
  1456. var batches = [[]];
  1457. target.forEach(function (obj) {
  1458. if (!obj.id) {
  1459. return;
  1460. }
  1461. batches[batches.length - 1].push(obj);
  1462. if (batches[batches.length - 1].length >= batchSize) {
  1463. batches.push([]);
  1464. }
  1465. });
  1466. if (batches[batches.length - 1].length === 0) {
  1467. batches.pop();
  1468. }
  1469. var deleteCompleted = Promise.resolve();
  1470. var errors = [];
  1471. batches.forEach(function (batch) {
  1472. deleteCompleted = deleteCompleted.then(function () {
  1473. return RESTController.request('POST', 'batch', {
  1474. requests: batch.map(function (obj) {
  1475. return {
  1476. method: 'DELETE',
  1477. path: getServerUrlPath() + 'classes/' + obj.className + '/' + obj._getId(),
  1478. body: {}
  1479. };
  1480. })
  1481. }, options).then(function (results) {
  1482. for (var i = 0; i < results.length; i++) {
  1483. if (results[i] && results[i].hasOwnProperty('error')) {
  1484. var err = new _ParseError.default(results[i].error.code, results[i].error.error);
  1485. err.object = batch[i];
  1486. errors.push(err);
  1487. }
  1488. }
  1489. });
  1490. });
  1491. });
  1492. return deleteCompleted.then((0, _asyncToGenerator2.default)(function* () {
  1493. if (errors.length) {
  1494. var aggregate = new _ParseError.default(_ParseError.default.AGGREGATE_ERROR);
  1495. aggregate.errors = errors;
  1496. return Promise.reject(aggregate);
  1497. }
  1498. for (var object of target) {
  1499. yield localDatastore._destroyObjectIfPinned(object);
  1500. }
  1501. return Promise.resolve(target);
  1502. }));
  1503. } else if (target instanceof ParseObject) {
  1504. return RESTController.request('DELETE', 'classes/' + target.className + '/' + target._getId(), {}, options).then((0, _asyncToGenerator2.default)(function* () {
  1505. yield localDatastore._destroyObjectIfPinned(target);
  1506. return Promise.resolve(target);
  1507. }));
  1508. }
  1509. return Promise.resolve(target);
  1510. });
  1511. function destroy() {
  1512. return _destroy.apply(this, arguments);
  1513. }
  1514. return destroy;
  1515. }(),
  1516. save: function (target, options) {
  1517. var batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
  1518. var localDatastore = _CoreManager.default.getLocalDatastore();
  1519. var mapIdForPin = {};
  1520. var RESTController = _CoreManager.default.getRESTController();
  1521. var stateController = _CoreManager.default.getObjectStateController();
  1522. var allowCustomObjectId = _CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID');
  1523. options = options || {};
  1524. options.returnStatus = options.returnStatus || true;
  1525. if (Array.isArray(target)) {
  1526. if (target.length < 1) {
  1527. return Promise.resolve([]);
  1528. }
  1529. var unsaved = target.concat();
  1530. for (var i = 0; i < target.length; i++) {
  1531. if (target[i] instanceof ParseObject) {
  1532. unsaved = unsaved.concat((0, _unsavedChildren.default)(target[i], true));
  1533. }
  1534. }
  1535. unsaved = (0, _unique.default)(unsaved);
  1536. var filesSaved = [];
  1537. var pending = [];
  1538. unsaved.forEach(function (el) {
  1539. if (el instanceof _ParseFile.default) {
  1540. filesSaved.push(el.save(options));
  1541. } else if (el instanceof ParseObject) {
  1542. pending.push(el);
  1543. }
  1544. });
  1545. return Promise.all(filesSaved).then(function () {
  1546. var objectError = null;
  1547. return (0, _promiseUtils.continueWhile)(function () {
  1548. return pending.length > 0;
  1549. }, function () {
  1550. var batch = [];
  1551. var nextPending = [];
  1552. pending.forEach(function (el) {
  1553. if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(el, 'id') && !el.id) {
  1554. throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null');
  1555. }
  1556. if (batch.length < batchSize && (0, _canBeSerialized.default)(el)) {
  1557. batch.push(el);
  1558. } else {
  1559. nextPending.push(el);
  1560. }
  1561. });
  1562. pending = nextPending;
  1563. if (batch.length < 1) {
  1564. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Tried to save a batch with a cycle.'));
  1565. }
  1566. var batchReturned = new _promiseUtils.resolvingPromise();
  1567. var batchReady = [];
  1568. var batchTasks = [];
  1569. batch.forEach(function (obj, index) {
  1570. var ready = new _promiseUtils.resolvingPromise();
  1571. batchReady.push(ready);
  1572. var task = function task() {
  1573. ready.resolve();
  1574. return batchReturned.then(function (responses) {
  1575. if (responses[index].hasOwnProperty('success')) {
  1576. var objectId = responses[index].success.objectId;
  1577. var status = responses[index]._status;
  1578. delete responses[index]._status;
  1579. mapIdForPin[objectId] = obj._localId;
  1580. obj._handleSaveResponse(responses[index].success, status);
  1581. } else {
  1582. if (!objectError && responses[index].hasOwnProperty('error')) {
  1583. var serverError = responses[index].error;
  1584. objectError = new _ParseError.default(serverError.code, serverError.error);
  1585. pending = [];
  1586. }
  1587. obj._handleSaveError();
  1588. }
  1589. });
  1590. };
  1591. stateController.pushPendingState(obj._getStateIdentifier());
  1592. batchTasks.push(stateController.enqueueTask(obj._getStateIdentifier(), task));
  1593. });
  1594. (0, _promiseUtils.when)(batchReady).then(function () {
  1595. return RESTController.request('POST', 'batch', {
  1596. requests: batch.map(function (obj) {
  1597. var params = obj._getSaveParams();
  1598. params.path = getServerUrlPath() + params.path;
  1599. return params;
  1600. })
  1601. }, options);
  1602. }).then(batchReturned.resolve, function (error) {
  1603. batchReturned.reject(new _ParseError.default(_ParseError.default.INCORRECT_TYPE, error.message));
  1604. });
  1605. return (0, _promiseUtils.when)(batchTasks);
  1606. }).then((0, _asyncToGenerator2.default)(function* () {
  1607. if (objectError) {
  1608. return Promise.reject(objectError);
  1609. }
  1610. for (var object of target) {
  1611. if (object instanceof ParseObject) {
  1612. yield localDatastore._updateLocalIdForObject(mapIdForPin[object.id], object);
  1613. yield localDatastore._updateObjectIfPinned(object);
  1614. }
  1615. }
  1616. return Promise.resolve(target);
  1617. }));
  1618. });
  1619. } else if (target instanceof ParseObject) {
  1620. if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(target, 'id') && !target.id) {
  1621. throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null');
  1622. }
  1623. target._getId();
  1624. var localId = target._localId;
  1625. var targetCopy = target;
  1626. var task = function task() {
  1627. var params = targetCopy._getSaveParams();
  1628. return RESTController.request(params.method, params.path, params.body, options).then(function (response) {
  1629. var status = response._status;
  1630. delete response._status;
  1631. targetCopy._handleSaveResponse(response, status);
  1632. }, function (error) {
  1633. targetCopy._handleSaveError();
  1634. return Promise.reject(error);
  1635. });
  1636. };
  1637. stateController.pushPendingState(target._getStateIdentifier());
  1638. return stateController.enqueueTask(target._getStateIdentifier(), task).then((0, _asyncToGenerator2.default)(function* () {
  1639. yield localDatastore._updateLocalIdForObject(localId, target);
  1640. yield localDatastore._updateObjectIfPinned(target);
  1641. return target;
  1642. }), function (error) {
  1643. return Promise.reject(error);
  1644. });
  1645. }
  1646. return Promise.resolve();
  1647. }
  1648. };
  1649. _CoreManager.default.setObjectController(DefaultController);
  1650. var _default = ParseObject;
  1651. exports.default = _default;