ParseObject.js 56 KB

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