ParseObject.js 62 KB

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