ParseObject.js 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  7. var _canBeSerialized = _interopRequireDefault(require("./canBeSerialized"));
  8. var _decode = _interopRequireDefault(require("./decode"));
  9. var _encode = _interopRequireDefault(require("./encode"));
  10. var _escape = _interopRequireDefault(require("./escape"));
  11. var _ParseACL = _interopRequireDefault(require("./ParseACL"));
  12. var _parseDate = _interopRequireDefault(require("./parseDate"));
  13. var _ParseError = _interopRequireDefault(require("./ParseError"));
  14. var _ParseFile = _interopRequireDefault(require("./ParseFile"));
  15. var _promiseUtils = require("./promiseUtils");
  16. var _LocalDatastoreUtils = require("./LocalDatastoreUtils");
  17. var _uuid = _interopRequireDefault(require("./uuid"));
  18. var _ParseOp = require("./ParseOp");
  19. var _ParseRelation = _interopRequireDefault(require("./ParseRelation"));
  20. var SingleInstanceStateController = _interopRequireWildcard(require("./SingleInstanceStateController"));
  21. var _unique = _interopRequireDefault(require("./unique"));
  22. var UniqueInstanceStateController = _interopRequireWildcard(require("./UniqueInstanceStateController"));
  23. var _unsavedChildren = _interopRequireDefault(require("./unsavedChildren"));
  24. function _getRequireWildcardCache(e) {
  25. if ("function" != typeof WeakMap) return null;
  26. var r = new WeakMap(),
  27. t = new WeakMap();
  28. return (_getRequireWildcardCache = function (e) {
  29. return e ? t : r;
  30. })(e);
  31. }
  32. function _interopRequireWildcard(e, r) {
  33. if (!r && e && e.__esModule) return e;
  34. if (null === e || "object" != typeof e && "function" != typeof e) return {
  35. default: e
  36. };
  37. var t = _getRequireWildcardCache(r);
  38. if (t && t.has(e)) return t.get(e);
  39. var n = {
  40. __proto__: null
  41. },
  42. a = Object.defineProperty && Object.getOwnPropertyDescriptor;
  43. for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
  44. var i = a ? Object.getOwnPropertyDescriptor(e, u) : null;
  45. i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u];
  46. }
  47. return n.default = e, t && t.set(e, n), n;
  48. }
  49. function _interopRequireDefault(e) {
  50. return e && e.__esModule ? e : {
  51. default: e
  52. };
  53. }
  54. // Mapping of class names to constructors, so we can populate objects from the
  55. // server with appropriate subclasses of ParseObject
  56. const classMap = {};
  57. // Global counter for generating unique Ids for non-single-instance objects
  58. let objectCount = 0;
  59. // On web clients, objects are single-instance: any two objects with the same Id
  60. // will have the same attributes. However, this may be dangerous default
  61. // behavior in a server scenario
  62. let singleInstance = !_CoreManager.default.get('IS_NODE');
  63. if (singleInstance) {
  64. _CoreManager.default.setObjectStateController(SingleInstanceStateController);
  65. } else {
  66. _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
  67. }
  68. function getServerUrlPath() {
  69. let serverUrl = _CoreManager.default.get('SERVER_URL');
  70. if (serverUrl[serverUrl.length - 1] !== '/') {
  71. serverUrl += '/';
  72. }
  73. const url = serverUrl.replace(/https?:\/\//, '');
  74. return url.substr(url.indexOf('/'));
  75. }
  76. /**
  77. * Creates a new model with defined attributes.
  78. *
  79. * <p>You won't normally call this method directly. It is recommended that
  80. * you use a subclass of <code>Parse.Object</code> instead, created by calling
  81. * <code>extend</code>.</p>
  82. *
  83. * <p>However, if you don't want to use a subclass, or aren't sure which
  84. * subclass is appropriate, you can use this form:<pre>
  85. * var object = new Parse.Object("ClassName");
  86. * </pre>
  87. * That is basically equivalent to:<pre>
  88. * var MyClass = Parse.Object.extend("ClassName");
  89. * var object = new MyClass();
  90. * </pre></p>
  91. *
  92. * @alias Parse.Object
  93. */
  94. class ParseObject {
  95. /**
  96. * @param {string} className The class name for the object
  97. * @param {object} attributes The initial set of data to store in the object.
  98. * @param {object} options The options for this object instance.
  99. * @param {boolean} [options.ignoreValidation] Set to `true` ignore any attribute validation errors.
  100. */
  101. constructor(className, attributes, options) {
  102. // Enable legacy initializers
  103. if (typeof this.initialize === 'function') {
  104. this.initialize.apply(this, arguments);
  105. }
  106. let toSet = null;
  107. this._objCount = objectCount++;
  108. if (typeof className === 'string') {
  109. this.className = className;
  110. if (attributes && typeof attributes === 'object') {
  111. toSet = attributes;
  112. }
  113. } else if (className && typeof className === 'object') {
  114. this.className = className.className;
  115. toSet = {};
  116. for (const attr in className) {
  117. if (attr !== 'className') {
  118. toSet[attr] = className[attr];
  119. }
  120. }
  121. if (attributes && typeof attributes === 'object') {
  122. options = attributes;
  123. }
  124. }
  125. if (toSet && !this.set(toSet, options)) {
  126. throw new Error("Can't create an invalid Parse Object");
  127. }
  128. }
  129. /**
  130. * The ID of this object, unique within its class.
  131. *
  132. * @property {string} id
  133. */
  134. /* Prototype getters / setters */
  135. get attributes() {
  136. const stateController = _CoreManager.default.getObjectStateController();
  137. return Object.freeze(stateController.estimateAttributes(this._getStateIdentifier()));
  138. }
  139. /**
  140. * The first time this object was saved on the server.
  141. *
  142. * @property {Date} createdAt
  143. * @returns {Date}
  144. */
  145. get createdAt() {
  146. return this._getServerData().createdAt;
  147. }
  148. /**
  149. * The last time this object was updated on the server.
  150. *
  151. * @property {Date} updatedAt
  152. * @returns {Date}
  153. */
  154. get updatedAt() {
  155. return this._getServerData().updatedAt;
  156. }
  157. /* Private methods */
  158. /**
  159. * Returns a local or server Id used uniquely identify this object
  160. *
  161. * @returns {string}
  162. */
  163. _getId() {
  164. if (typeof this.id === 'string') {
  165. return this.id;
  166. }
  167. if (typeof this._localId === 'string') {
  168. return this._localId;
  169. }
  170. const localId = 'local' + (0, _uuid.default)();
  171. this._localId = localId;
  172. return localId;
  173. }
  174. /**
  175. * Returns a unique identifier used to pull data from the State Controller.
  176. *
  177. * @returns {Parse.Object|object}
  178. */
  179. _getStateIdentifier() {
  180. if (singleInstance) {
  181. let id = this.id;
  182. if (!id) {
  183. id = this._getId();
  184. }
  185. return {
  186. id: id,
  187. className: this.className
  188. };
  189. } else {
  190. return this;
  191. }
  192. }
  193. _getServerData() {
  194. const stateController = _CoreManager.default.getObjectStateController();
  195. return stateController.getServerData(this._getStateIdentifier());
  196. }
  197. _clearServerData() {
  198. const serverData = this._getServerData();
  199. const unset = {};
  200. for (const attr in serverData) {
  201. unset[attr] = undefined;
  202. }
  203. const stateController = _CoreManager.default.getObjectStateController();
  204. stateController.setServerData(this._getStateIdentifier(), unset);
  205. }
  206. _getPendingOps() {
  207. const stateController = _CoreManager.default.getObjectStateController();
  208. return stateController.getPendingOps(this._getStateIdentifier());
  209. }
  210. /**
  211. * @param {Array<string>} [keysToClear] - if specified, only ops matching
  212. * these fields will be cleared
  213. */
  214. _clearPendingOps(keysToClear) {
  215. const pending = this._getPendingOps();
  216. const latest = pending[pending.length - 1];
  217. const keys = keysToClear || Object.keys(latest);
  218. keys.forEach(key => {
  219. delete latest[key];
  220. });
  221. }
  222. _getDirtyObjectAttributes() {
  223. const attributes = this.attributes;
  224. const stateController = _CoreManager.default.getObjectStateController();
  225. const objectCache = stateController.getObjectCache(this._getStateIdentifier());
  226. const dirty = {};
  227. for (const attr in attributes) {
  228. const val = attributes[attr];
  229. if (val && typeof val === 'object' && !(val instanceof ParseObject) && !(val instanceof _ParseFile.default) && !(val instanceof _ParseRelation.default)) {
  230. // Due to the way browsers construct maps, the key order will not change
  231. // unless the object is changed
  232. try {
  233. const json = (0, _encode.default)(val, false, true);
  234. const stringified = JSON.stringify(json);
  235. if (objectCache[attr] !== stringified) {
  236. dirty[attr] = val;
  237. }
  238. } catch (e) {
  239. // Error occurred, possibly by a nested unsaved pointer in a mutable container
  240. // No matter how it happened, it indicates a change in the attribute
  241. dirty[attr] = val;
  242. }
  243. }
  244. }
  245. return dirty;
  246. }
  247. _toFullJSON(seen, offline) {
  248. const json = this.toJSON(seen, offline);
  249. json.__type = 'Object';
  250. json.className = this.className;
  251. return json;
  252. }
  253. _getSaveJSON() {
  254. const pending = this._getPendingOps();
  255. const dirtyObjects = this._getDirtyObjectAttributes();
  256. const json = {};
  257. for (var attr in dirtyObjects) {
  258. let isDotNotation = false;
  259. for (let i = 0; i < pending.length; i += 1) {
  260. for (const field in pending[i]) {
  261. // Dot notation operations are handled later
  262. if (field.includes('.')) {
  263. const fieldName = field.split('.')[0];
  264. if (fieldName === attr) {
  265. isDotNotation = true;
  266. break;
  267. }
  268. }
  269. }
  270. }
  271. if (!isDotNotation) {
  272. json[attr] = new _ParseOp.SetOp(dirtyObjects[attr]).toJSON();
  273. }
  274. }
  275. for (attr in pending[0]) {
  276. json[attr] = pending[0][attr].toJSON();
  277. }
  278. return json;
  279. }
  280. _getSaveParams() {
  281. let method = this.id ? 'PUT' : 'POST';
  282. const body = this._getSaveJSON();
  283. let path = 'classes/' + this.className;
  284. if (_CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID')) {
  285. if (!this.createdAt) {
  286. method = 'POST';
  287. body.objectId = this.id;
  288. } else {
  289. method = 'PUT';
  290. path += '/' + this.id;
  291. }
  292. } else if (this.id) {
  293. path += '/' + this.id;
  294. } else if (this.className === '_User') {
  295. path = 'users';
  296. }
  297. return {
  298. method,
  299. body,
  300. path
  301. };
  302. }
  303. _finishFetch(serverData) {
  304. if (!this.id && serverData.objectId) {
  305. this.id = serverData.objectId;
  306. }
  307. const stateController = _CoreManager.default.getObjectStateController();
  308. stateController.initializeState(this._getStateIdentifier());
  309. const decoded = {};
  310. for (const attr in serverData) {
  311. if (attr === 'ACL') {
  312. decoded[attr] = new _ParseACL.default(serverData[attr]);
  313. } else if (attr !== 'objectId') {
  314. decoded[attr] = (0, _decode.default)(serverData[attr]);
  315. if (decoded[attr] instanceof _ParseRelation.default) {
  316. decoded[attr]._ensureParentAndKey(this, attr);
  317. }
  318. }
  319. }
  320. if (decoded.createdAt && typeof decoded.createdAt === 'string') {
  321. decoded.createdAt = (0, _parseDate.default)(decoded.createdAt);
  322. }
  323. if (decoded.updatedAt && typeof decoded.updatedAt === 'string') {
  324. decoded.updatedAt = (0, _parseDate.default)(decoded.updatedAt);
  325. }
  326. if (!decoded.updatedAt && decoded.createdAt) {
  327. decoded.updatedAt = decoded.createdAt;
  328. }
  329. stateController.commitServerChanges(this._getStateIdentifier(), decoded);
  330. }
  331. _setExisted(existed) {
  332. const stateController = _CoreManager.default.getObjectStateController();
  333. const state = stateController.getState(this._getStateIdentifier());
  334. if (state) {
  335. state.existed = existed;
  336. }
  337. }
  338. _migrateId(serverId) {
  339. if (this._localId && serverId) {
  340. if (singleInstance) {
  341. const stateController = _CoreManager.default.getObjectStateController();
  342. const oldState = stateController.removeState(this._getStateIdentifier());
  343. this.id = serverId;
  344. delete this._localId;
  345. if (oldState) {
  346. stateController.initializeState(this._getStateIdentifier(), oldState);
  347. }
  348. } else {
  349. this.id = serverId;
  350. delete this._localId;
  351. }
  352. }
  353. }
  354. _handleSaveResponse(response, status) {
  355. const changes = {};
  356. const stateController = _CoreManager.default.getObjectStateController();
  357. const pending = stateController.popPendingState(this._getStateIdentifier());
  358. for (var attr in pending) {
  359. if (pending[attr] instanceof _ParseOp.RelationOp) {
  360. changes[attr] = pending[attr].applyTo(undefined, this, attr);
  361. } else if (!(attr in response)) {
  362. // Only SetOps and UnsetOps should not come back with results
  363. changes[attr] = pending[attr].applyTo(undefined);
  364. }
  365. }
  366. for (attr in response) {
  367. if ((attr === 'createdAt' || attr === 'updatedAt') && typeof response[attr] === 'string') {
  368. changes[attr] = (0, _parseDate.default)(response[attr]);
  369. } else if (attr === 'ACL') {
  370. changes[attr] = new _ParseACL.default(response[attr]);
  371. } else if (attr !== 'objectId') {
  372. const val = (0, _decode.default)(response[attr]);
  373. if (val && Object.getPrototypeOf(val) === Object.prototype) {
  374. changes[attr] = {
  375. ...this.attributes[attr],
  376. ...val
  377. };
  378. } else {
  379. changes[attr] = val;
  380. }
  381. if (changes[attr] instanceof _ParseOp.UnsetOp) {
  382. changes[attr] = undefined;
  383. }
  384. }
  385. }
  386. if (changes.createdAt && !changes.updatedAt) {
  387. changes.updatedAt = changes.createdAt;
  388. }
  389. this._migrateId(response.objectId);
  390. if (status !== 201) {
  391. this._setExisted(true);
  392. }
  393. stateController.commitServerChanges(this._getStateIdentifier(), changes);
  394. }
  395. _handleSaveError() {
  396. const stateController = _CoreManager.default.getObjectStateController();
  397. stateController.mergeFirstPendingState(this._getStateIdentifier());
  398. }
  399. static _getClassMap() {
  400. return classMap;
  401. }
  402. /* Public methods */
  403. initialize() {
  404. // NOOP
  405. }
  406. /**
  407. * Returns a JSON version of the object suitable for saving to Parse.
  408. *
  409. * @param seen
  410. * @param offline
  411. * @returns {object}
  412. */
  413. toJSON(seen, offline) {
  414. const seenEntry = this.id ? this.className + ':' + this.id : this;
  415. seen = seen || [seenEntry];
  416. const json = {};
  417. const attrs = this.attributes;
  418. for (const attr in attrs) {
  419. if ((attr === 'createdAt' || attr === 'updatedAt') && attrs[attr].toJSON) {
  420. json[attr] = attrs[attr].toJSON();
  421. } else {
  422. json[attr] = (0, _encode.default)(attrs[attr], false, false, seen, offline);
  423. }
  424. }
  425. const pending = this._getPendingOps();
  426. for (const attr in pending[0]) {
  427. if (attr.indexOf('.') < 0) {
  428. json[attr] = pending[0][attr].toJSON(offline);
  429. }
  430. }
  431. if (this.id) {
  432. json.objectId = this.id;
  433. }
  434. return json;
  435. }
  436. /**
  437. * Determines whether this ParseObject is equal to another ParseObject
  438. *
  439. * @param {object} other - An other object ot compare
  440. * @returns {boolean}
  441. */
  442. equals(other) {
  443. if (this === other) {
  444. return true;
  445. }
  446. return other instanceof ParseObject && this.className === other.className && this.id === other.id && typeof this.id !== 'undefined';
  447. }
  448. /**
  449. * Returns true if this object has been modified since its last
  450. * save/refresh. If an attribute is specified, it returns true only if that
  451. * particular attribute has been modified since the last save/refresh.
  452. *
  453. * @param {string} attr An attribute name (optional).
  454. * @returns {boolean}
  455. */
  456. dirty(attr) {
  457. if (!this.id) {
  458. return true;
  459. }
  460. const pendingOps = this._getPendingOps();
  461. const dirtyObjects = this._getDirtyObjectAttributes();
  462. if (attr) {
  463. if (dirtyObjects.hasOwnProperty(attr)) {
  464. return true;
  465. }
  466. for (let i = 0; i < pendingOps.length; i++) {
  467. if (pendingOps[i].hasOwnProperty(attr)) {
  468. return true;
  469. }
  470. }
  471. return false;
  472. }
  473. if (Object.keys(pendingOps[0]).length !== 0) {
  474. return true;
  475. }
  476. if (Object.keys(dirtyObjects).length !== 0) {
  477. return true;
  478. }
  479. return false;
  480. }
  481. /**
  482. * Returns an array of keys that have been modified since last save/refresh
  483. *
  484. * @returns {string[]}
  485. */
  486. dirtyKeys() {
  487. const pendingOps = this._getPendingOps();
  488. const keys = {};
  489. for (let i = 0; i < pendingOps.length; i++) {
  490. for (const attr in pendingOps[i]) {
  491. keys[attr] = true;
  492. }
  493. }
  494. const dirtyObjects = this._getDirtyObjectAttributes();
  495. for (const attr in dirtyObjects) {
  496. keys[attr] = true;
  497. }
  498. return Object.keys(keys);
  499. }
  500. /**
  501. * Returns true if the object has been fetched.
  502. *
  503. * @returns {boolean}
  504. */
  505. isDataAvailable() {
  506. const serverData = this._getServerData();
  507. return !!Object.keys(serverData).length;
  508. }
  509. /**
  510. * Gets a Pointer referencing this Object.
  511. *
  512. * @returns {Pointer}
  513. */
  514. toPointer() {
  515. if (!this.id) {
  516. throw new Error('Cannot create a pointer to an unsaved ParseObject');
  517. }
  518. return {
  519. __type: 'Pointer',
  520. className: this.className,
  521. objectId: this.id
  522. };
  523. }
  524. /**
  525. * Gets a Pointer referencing this Object.
  526. *
  527. * @returns {Pointer}
  528. */
  529. toOfflinePointer() {
  530. if (!this._localId) {
  531. throw new Error('Cannot create a offline pointer to a saved ParseObject');
  532. }
  533. return {
  534. __type: 'Object',
  535. className: this.className,
  536. _localId: this._localId
  537. };
  538. }
  539. /**
  540. * Gets the value of an attribute.
  541. *
  542. * @param {string} attr The string name of an attribute.
  543. * @returns {*}
  544. */
  545. get(attr) {
  546. return this.attributes[attr];
  547. }
  548. /**
  549. * Gets a relation on the given class for the attribute.
  550. *
  551. * @param {string} attr The attribute to get the relation for.
  552. * @returns {Parse.Relation}
  553. */
  554. relation(attr) {
  555. const value = this.get(attr);
  556. if (value) {
  557. if (!(value instanceof _ParseRelation.default)) {
  558. throw new Error('Called relation() on non-relation field ' + attr);
  559. }
  560. value._ensureParentAndKey(this, attr);
  561. return value;
  562. }
  563. return new _ParseRelation.default(this, attr);
  564. }
  565. /**
  566. * Gets the HTML-escaped value of an attribute.
  567. *
  568. * @param {string} attr The string name of an attribute.
  569. * @returns {string}
  570. */
  571. escape(attr) {
  572. let val = this.attributes[attr];
  573. if (val == null) {
  574. return '';
  575. }
  576. if (typeof val !== 'string') {
  577. if (typeof val.toString !== 'function') {
  578. return '';
  579. }
  580. val = val.toString();
  581. }
  582. return (0, _escape.default)(val);
  583. }
  584. /**
  585. * Returns <code>true</code> if the attribute contains a value that is not
  586. * null or undefined.
  587. *
  588. * @param {string} attr The string name of the attribute.
  589. * @returns {boolean}
  590. */
  591. has(attr) {
  592. const attributes = this.attributes;
  593. if (attributes.hasOwnProperty(attr)) {
  594. return attributes[attr] != null;
  595. }
  596. return false;
  597. }
  598. /**
  599. * Sets a hash of model attributes on the object.
  600. *
  601. * <p>You can call it with an object containing keys and values, with one
  602. * key and value, or dot notation. For example:<pre>
  603. * gameTurn.set({
  604. * player: player1,
  605. * diceRoll: 2
  606. * }, {
  607. * error: function(gameTurnAgain, error) {
  608. * // The set failed validation.
  609. * }
  610. * });
  611. *
  612. * game.set("currentPlayer", player2, {
  613. * error: function(gameTurnAgain, error) {
  614. * // The set failed validation.
  615. * }
  616. * });
  617. *
  618. * game.set("finished", true);</pre></p>
  619. *
  620. * game.set("player.score", 10);</pre></p>
  621. *
  622. * @param {(string|object)} key The key to set.
  623. * @param {(string|object)} value The value to give it.
  624. * @param {object} options A set of options for the set.
  625. * The only supported option is <code>error</code>.
  626. * @returns {(ParseObject|boolean)} true if the set succeeded.
  627. */
  628. set(key, value, options) {
  629. let changes = {};
  630. const newOps = {};
  631. if (key && typeof key === 'object') {
  632. changes = key;
  633. options = value;
  634. } else if (typeof key === 'string') {
  635. changes[key] = value;
  636. } else {
  637. return this;
  638. }
  639. options = options || {};
  640. let readonly = [];
  641. if (typeof this.constructor.readOnlyAttributes === 'function') {
  642. readonly = readonly.concat(this.constructor.readOnlyAttributes());
  643. }
  644. for (const k in changes) {
  645. if (k === 'createdAt' || k === 'updatedAt') {
  646. // This property is read-only, but for legacy reasons we silently
  647. // ignore it
  648. continue;
  649. }
  650. if (readonly.indexOf(k) > -1) {
  651. throw new Error('Cannot modify readonly attribute: ' + k);
  652. }
  653. if (options.unset) {
  654. newOps[k] = new _ParseOp.UnsetOp();
  655. } else if (changes[k] instanceof _ParseOp.Op) {
  656. newOps[k] = changes[k];
  657. } else if (changes[k] && typeof changes[k] === 'object' && typeof changes[k].__op === 'string') {
  658. newOps[k] = (0, _ParseOp.opFromJSON)(changes[k]);
  659. } else if (k === 'objectId' || k === 'id') {
  660. if (typeof changes[k] === 'string') {
  661. this.id = changes[k];
  662. }
  663. } else if (k === 'ACL' && typeof changes[k] === 'object' && !(changes[k] instanceof _ParseACL.default)) {
  664. newOps[k] = new _ParseOp.SetOp(new _ParseACL.default(changes[k]));
  665. } else if (changes[k] instanceof _ParseRelation.default) {
  666. const relation = new _ParseRelation.default(this, k);
  667. relation.targetClassName = changes[k].targetClassName;
  668. newOps[k] = new _ParseOp.SetOp(relation);
  669. } else {
  670. newOps[k] = new _ParseOp.SetOp(changes[k]);
  671. }
  672. }
  673. const currentAttributes = this.attributes;
  674. // Calculate new values
  675. const newValues = {};
  676. for (const attr in newOps) {
  677. if (newOps[attr] instanceof _ParseOp.RelationOp) {
  678. newValues[attr] = newOps[attr].applyTo(currentAttributes[attr], this, attr);
  679. } else if (!(newOps[attr] instanceof _ParseOp.UnsetOp)) {
  680. newValues[attr] = newOps[attr].applyTo(currentAttributes[attr]);
  681. }
  682. }
  683. // Validate changes
  684. if (!options.ignoreValidation) {
  685. const validation = this.validate(newValues);
  686. if (validation) {
  687. if (typeof options.error === 'function') {
  688. options.error(this, validation);
  689. }
  690. return false;
  691. }
  692. }
  693. // Consolidate Ops
  694. const pendingOps = this._getPendingOps();
  695. const last = pendingOps.length - 1;
  696. const stateController = _CoreManager.default.getObjectStateController();
  697. for (const attr in newOps) {
  698. const nextOp = newOps[attr].mergeWith(pendingOps[last][attr]);
  699. stateController.setPendingOp(this._getStateIdentifier(), attr, nextOp);
  700. }
  701. return this;
  702. }
  703. /**
  704. * Remove an attribute from the model. This is a noop if the attribute doesn't
  705. * exist.
  706. *
  707. * @param {string} attr The string name of an attribute.
  708. * @param options
  709. * @returns {(ParseObject | boolean)}
  710. */
  711. unset(attr, options) {
  712. options = options || {};
  713. options.unset = true;
  714. return this.set(attr, null, options);
  715. }
  716. /**
  717. * Atomically increments the value of the given attribute the next time the
  718. * object is saved. If no amount is specified, 1 is used by default.
  719. *
  720. * @param attr {String} The key.
  721. * @param amount {Number} The amount to increment by (optional).
  722. * @returns {(ParseObject|boolean)}
  723. */
  724. increment(attr, amount) {
  725. if (typeof amount === 'undefined') {
  726. amount = 1;
  727. }
  728. if (typeof amount !== 'number') {
  729. throw new Error('Cannot increment by a non-numeric amount.');
  730. }
  731. return this.set(attr, new _ParseOp.IncrementOp(amount));
  732. }
  733. /**
  734. * Atomically decrements the value of the given attribute the next time the
  735. * object is saved. If no amount is specified, 1 is used by default.
  736. *
  737. * @param attr {String} The key.
  738. * @param amount {Number} The amount to decrement by (optional).
  739. * @returns {(ParseObject | boolean)}
  740. */
  741. decrement(attr, amount) {
  742. if (typeof amount === 'undefined') {
  743. amount = 1;
  744. }
  745. if (typeof amount !== 'number') {
  746. throw new Error('Cannot decrement by a non-numeric amount.');
  747. }
  748. return this.set(attr, new _ParseOp.IncrementOp(amount * -1));
  749. }
  750. /**
  751. * Atomically add an object to the end of the array associated with a given
  752. * key.
  753. *
  754. * @param attr {String} The key.
  755. * @param item {} The item to add.
  756. * @returns {(ParseObject | boolean)}
  757. */
  758. add(attr, item) {
  759. return this.set(attr, new _ParseOp.AddOp([item]));
  760. }
  761. /**
  762. * Atomically add the objects to the end of the array associated with a given
  763. * key.
  764. *
  765. * @param attr {String} The key.
  766. * @param items {Object[]} The items to add.
  767. * @returns {(ParseObject | boolean)}
  768. */
  769. addAll(attr, items) {
  770. return this.set(attr, new _ParseOp.AddOp(items));
  771. }
  772. /**
  773. * Atomically add an object to the array associated with a given key, only
  774. * if it is not already present in the array. The position of the insert is
  775. * not guaranteed.
  776. *
  777. * @param attr {String} The key.
  778. * @param item {} The object to add.
  779. * @returns {(ParseObject | boolean)}
  780. */
  781. addUnique(attr, item) {
  782. return this.set(attr, new _ParseOp.AddUniqueOp([item]));
  783. }
  784. /**
  785. * Atomically add the objects to the array associated with a given key, only
  786. * if it is not already present in the array. The position of the insert is
  787. * not guaranteed.
  788. *
  789. * @param attr {String} The key.
  790. * @param items {Object[]} The objects to add.
  791. * @returns {(ParseObject | boolean)}
  792. */
  793. addAllUnique(attr, items) {
  794. return this.set(attr, new _ParseOp.AddUniqueOp(items));
  795. }
  796. /**
  797. * Atomically remove all instances of an object from the array associated
  798. * with a given key.
  799. *
  800. * @param attr {String} The key.
  801. * @param item {} The object to remove.
  802. * @returns {(ParseObject | boolean)}
  803. */
  804. remove(attr, item) {
  805. return this.set(attr, new _ParseOp.RemoveOp([item]));
  806. }
  807. /**
  808. * Atomically remove all instances of the objects from the array associated
  809. * with a given key.
  810. *
  811. * @param attr {String} The key.
  812. * @param items {Object[]} The object to remove.
  813. * @returns {(ParseObject | boolean)}
  814. */
  815. removeAll(attr, items) {
  816. return this.set(attr, new _ParseOp.RemoveOp(items));
  817. }
  818. /**
  819. * Returns an instance of a subclass of Parse.Op describing what kind of
  820. * modification has been performed on this field since the last time it was
  821. * saved. For example, after calling object.increment("x"), calling
  822. * object.op("x") would return an instance of Parse.Op.Increment.
  823. *
  824. * @param attr {String} The key.
  825. * @returns {Parse.Op | undefined} The operation, or undefined if none.
  826. */
  827. op(attr) {
  828. const pending = this._getPendingOps();
  829. for (let i = pending.length; i--;) {
  830. if (pending[i][attr]) {
  831. return pending[i][attr];
  832. }
  833. }
  834. }
  835. /**
  836. * Creates a new model with identical attributes to this one.
  837. *
  838. * @returns {Parse.Object}
  839. */
  840. clone() {
  841. const clone = new this.constructor(this.className);
  842. let attributes = this.attributes;
  843. if (typeof this.constructor.readOnlyAttributes === 'function') {
  844. const readonly = this.constructor.readOnlyAttributes() || [];
  845. // Attributes are frozen, so we have to rebuild an object,
  846. // rather than delete readonly keys
  847. const copy = {};
  848. for (const a in attributes) {
  849. if (readonly.indexOf(a) < 0) {
  850. copy[a] = attributes[a];
  851. }
  852. }
  853. attributes = copy;
  854. }
  855. if (clone.set) {
  856. clone.set(attributes);
  857. }
  858. return clone;
  859. }
  860. /**
  861. * Creates a new instance of this object. Not to be confused with clone()
  862. *
  863. * @returns {Parse.Object}
  864. */
  865. newInstance() {
  866. const clone = new this.constructor(this.className);
  867. clone.id = this.id;
  868. if (singleInstance) {
  869. // Just return an object with the right id
  870. return clone;
  871. }
  872. const stateController = _CoreManager.default.getObjectStateController();
  873. if (stateController) {
  874. stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier());
  875. }
  876. return clone;
  877. }
  878. /**
  879. * Returns true if this object has never been saved to Parse.
  880. *
  881. * @returns {boolean}
  882. */
  883. isNew() {
  884. return !this.id;
  885. }
  886. /**
  887. * Returns true if this object was created by the Parse server when the
  888. * object might have already been there (e.g. in the case of a Facebook
  889. * login)
  890. *
  891. * @returns {boolean}
  892. */
  893. existed() {
  894. if (!this.id) {
  895. return false;
  896. }
  897. const stateController = _CoreManager.default.getObjectStateController();
  898. const state = stateController.getState(this._getStateIdentifier());
  899. if (state) {
  900. return state.existed;
  901. }
  902. return false;
  903. }
  904. /**
  905. * Returns true if this object exists on the Server
  906. *
  907. * @param {object} options
  908. * Valid options are:<ul>
  909. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  910. * be used for this request.
  911. * <li>sessionToken: A valid session token, used for making a request on
  912. * behalf of a specific user.
  913. * </ul>
  914. * @returns {Promise<boolean>} A boolean promise that is fulfilled if object exists.
  915. */
  916. async exists(options) {
  917. if (!this.id) {
  918. return false;
  919. }
  920. try {
  921. const ParseQuery = _CoreManager.default.getParseQuery();
  922. const query = new ParseQuery(this.className);
  923. await query.get(this.id, options);
  924. return true;
  925. } catch (e) {
  926. if (e.code === _ParseError.default.OBJECT_NOT_FOUND) {
  927. return false;
  928. }
  929. throw e;
  930. }
  931. }
  932. /**
  933. * Checks if the model is currently in a valid state.
  934. *
  935. * @returns {boolean}
  936. */
  937. isValid() {
  938. return !this.validate(this.attributes);
  939. }
  940. /**
  941. * You should not call this function directly unless you subclass
  942. * <code>Parse.Object</code>, in which case you can override this method
  943. * to provide additional validation on <code>set</code> and
  944. * <code>save</code>. Your implementation should return
  945. *
  946. * @param {object} attrs The current data to validate.
  947. * @returns {Parse.Error|boolean} False if the data is valid. An error object otherwise.
  948. * @see Parse.Object#set
  949. */
  950. validate(attrs) {
  951. if (attrs.hasOwnProperty('ACL') && !(attrs.ACL instanceof _ParseACL.default)) {
  952. return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'ACL must be a Parse ACL.');
  953. }
  954. for (const key in attrs) {
  955. if (!/^[A-Za-z][0-9A-Za-z_.]*$/.test(key)) {
  956. return new _ParseError.default(_ParseError.default.INVALID_KEY_NAME);
  957. }
  958. }
  959. return false;
  960. }
  961. /**
  962. * Returns the ACL for this object.
  963. *
  964. * @returns {Parse.ACL|null} An instance of Parse.ACL.
  965. * @see Parse.Object#get
  966. */
  967. getACL() {
  968. const acl = this.get('ACL');
  969. if (acl instanceof _ParseACL.default) {
  970. return acl;
  971. }
  972. return null;
  973. }
  974. /**
  975. * Sets the ACL to be used for this object.
  976. *
  977. * @param {Parse.ACL} acl An instance of Parse.ACL.
  978. * @param {object} options
  979. * @returns {(ParseObject | boolean)} Whether the set passed validation.
  980. * @see Parse.Object#set
  981. */
  982. setACL(acl, options) {
  983. return this.set('ACL', acl, options);
  984. }
  985. /**
  986. * Clears any (or specific) changes to this object made since the last call to save()
  987. *
  988. * @param {string} [keys] - specify which fields to revert
  989. */
  990. revert(...keys) {
  991. let keysToRevert;
  992. if (keys.length) {
  993. keysToRevert = [];
  994. for (const key of keys) {
  995. if (typeof key === 'string') {
  996. keysToRevert.push(key);
  997. } else {
  998. throw new Error('Parse.Object#revert expects either no, or a list of string, arguments.');
  999. }
  1000. }
  1001. }
  1002. this._clearPendingOps(keysToRevert);
  1003. }
  1004. /**
  1005. * Clears all attributes on a model
  1006. *
  1007. * @returns {(ParseObject | boolean)}
  1008. */
  1009. clear() {
  1010. const attributes = this.attributes;
  1011. const erasable = {};
  1012. let readonly = ['createdAt', 'updatedAt'];
  1013. if (typeof this.constructor.readOnlyAttributes === 'function') {
  1014. readonly = readonly.concat(this.constructor.readOnlyAttributes());
  1015. }
  1016. for (const attr in attributes) {
  1017. if (readonly.indexOf(attr) < 0) {
  1018. erasable[attr] = true;
  1019. }
  1020. }
  1021. return this.set(erasable, {
  1022. unset: true
  1023. });
  1024. }
  1025. /**
  1026. * Fetch the model from the server. If the server's representation of the
  1027. * model differs from its current attributes, they will be overriden.
  1028. *
  1029. * @param {object} options
  1030. * Valid options are:<ul>
  1031. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1032. * be used for this request.
  1033. * <li>sessionToken: A valid session token, used for making a request on
  1034. * behalf of a specific user.
  1035. * <li>include: The name(s) of the key(s) to include. Can be a string, an array of strings,
  1036. * or an array of array of strings.
  1037. * <li>context: A dictionary that is accessible in Cloud Code `beforeFind` trigger.
  1038. * </ul>
  1039. * @returns {Promise} A promise that is fulfilled when the fetch
  1040. * completes.
  1041. */
  1042. fetch(options) {
  1043. options = options || {};
  1044. const fetchOptions = {};
  1045. if (options.hasOwnProperty('useMasterKey')) {
  1046. fetchOptions.useMasterKey = options.useMasterKey;
  1047. }
  1048. if (options.hasOwnProperty('sessionToken')) {
  1049. fetchOptions.sessionToken = options.sessionToken;
  1050. }
  1051. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  1052. fetchOptions.context = options.context;
  1053. }
  1054. if (options.hasOwnProperty('include')) {
  1055. fetchOptions.include = [];
  1056. if (Array.isArray(options.include)) {
  1057. options.include.forEach(key => {
  1058. if (Array.isArray(key)) {
  1059. fetchOptions.include = fetchOptions.include.concat(key);
  1060. } else {
  1061. fetchOptions.include.push(key);
  1062. }
  1063. });
  1064. } else {
  1065. fetchOptions.include.push(options.include);
  1066. }
  1067. }
  1068. const controller = _CoreManager.default.getObjectController();
  1069. return controller.fetch(this, true, fetchOptions);
  1070. }
  1071. /**
  1072. * Fetch the model from the server. If the server's representation of the
  1073. * model differs from its current attributes, they will be overriden.
  1074. *
  1075. * Includes nested Parse.Objects for the provided key. You can use dot
  1076. * notation to specify which fields in the included object are also fetched.
  1077. *
  1078. * @param {string | Array<string | Array<string>>} keys The name(s) of the key(s) to include.
  1079. * @param {object} options
  1080. * Valid options are:<ul>
  1081. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1082. * be used for this request.
  1083. * <li>sessionToken: A valid session token, used for making a request on
  1084. * behalf of a specific user.
  1085. * </ul>
  1086. * @returns {Promise} A promise that is fulfilled when the fetch
  1087. * completes.
  1088. */
  1089. fetchWithInclude(keys, options) {
  1090. options = options || {};
  1091. options.include = keys;
  1092. return this.fetch(options);
  1093. }
  1094. /**
  1095. * Saves this object to the server at some unspecified time in the future,
  1096. * even if Parse is currently inaccessible.
  1097. *
  1098. * Use this when you may not have a solid network connection, and don't need to know when the save completes.
  1099. * If there is some problem with the object such that it can't be saved, it will be silently discarded.
  1100. *
  1101. * Objects saved with this method will be stored locally in an on-disk cache until they can be delivered to Parse.
  1102. * They will be sent immediately if possible. Otherwise, they will be sent the next time a network connection is
  1103. * available. Objects saved this way will persist even after the app is closed, in which case they will be sent the
  1104. * next time the app is opened.
  1105. *
  1106. * @param {object} [options]
  1107. * Used to pass option parameters to method if arg1 and arg2 were both passed as strings.
  1108. * Valid options are:
  1109. * <ul>
  1110. * <li>sessionToken: A valid session token, used for making a request on
  1111. * behalf of a specific user.
  1112. * <li>cascadeSave: If `false`, nested objects will not be saved (default is `true`).
  1113. * <li>context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers.
  1114. * </ul>
  1115. * @returns {Promise} A promise that is fulfilled when the save
  1116. * completes.
  1117. */
  1118. async saveEventually(options) {
  1119. try {
  1120. await this.save(null, options);
  1121. } catch (e) {
  1122. if (e.code === _ParseError.default.CONNECTION_FAILED) {
  1123. await _CoreManager.default.getEventuallyQueue().save(this, options);
  1124. _CoreManager.default.getEventuallyQueue().poll();
  1125. }
  1126. }
  1127. return this;
  1128. }
  1129. /**
  1130. * Set a hash of model attributes, and save the model to the server.
  1131. * updatedAt will be updated when the request returns.
  1132. * You can either call it as:<pre>
  1133. * object.save();</pre>
  1134. * or<pre>
  1135. * object.save(attrs);</pre>
  1136. * or<pre>
  1137. * object.save(null, options);</pre>
  1138. * or<pre>
  1139. * object.save(attrs, options);</pre>
  1140. * or<pre>
  1141. * object.save(key, value);</pre>
  1142. * or<pre>
  1143. * object.save(key, value, options);</pre>
  1144. *
  1145. * Example 1: <pre>
  1146. * gameTurn.save({
  1147. * player: "Jake Cutter",
  1148. * diceRoll: 2
  1149. * }).then(function(gameTurnAgain) {
  1150. * // The save was successful.
  1151. * }, function(error) {
  1152. * // The save failed. Error is an instance of Parse.Error.
  1153. * });</pre>
  1154. *
  1155. * Example 2: <pre>
  1156. * gameTurn.save("player", "Jake Cutter");</pre>
  1157. *
  1158. * @param {string | object | null} [arg1]
  1159. * Valid options are:<ul>
  1160. * <li>`Object` - Key/value pairs to update on the object.</li>
  1161. * <li>`String` Key - Key of attribute to update (requires arg2 to also be string)</li>
  1162. * <li>`null` - Passing null for arg1 allows you to save the object with options passed in arg2.</li>
  1163. * </ul>
  1164. * @param {string | object} [arg2]
  1165. * <ul>
  1166. * <li>`String` Value - If arg1 was passed as a key, arg2 is the value that should be set on that key.</li>
  1167. * <li>`Object` Options - Valid options are:
  1168. * <ul>
  1169. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1170. * be used for this request.
  1171. * <li>sessionToken: A valid session token, used for making a request on
  1172. * behalf of a specific user.
  1173. * <li>cascadeSave: If `false`, nested objects will not be saved (default is `true`).
  1174. * <li>context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers.
  1175. * </ul>
  1176. * </li>
  1177. * </ul>
  1178. * @param {object} [arg3]
  1179. * Used to pass option parameters to method if arg1 and arg2 were both passed as strings.
  1180. * Valid options are:
  1181. * <ul>
  1182. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1183. * be used for this request.
  1184. * <li>sessionToken: A valid session token, used for making a request on
  1185. * behalf of a specific user.
  1186. * <li>cascadeSave: If `false`, nested objects will not be saved (default is `true`).
  1187. * <li>context: A dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers.
  1188. * </ul>
  1189. * @returns {Promise} A promise that is fulfilled when the save
  1190. * completes.
  1191. */
  1192. save(arg1, arg2, arg3) {
  1193. let attrs;
  1194. let options;
  1195. if (typeof arg1 === 'object' || typeof arg1 === 'undefined') {
  1196. attrs = arg1;
  1197. if (typeof arg2 === 'object') {
  1198. options = arg2;
  1199. }
  1200. } else {
  1201. attrs = {};
  1202. attrs[arg1] = arg2;
  1203. options = arg3;
  1204. }
  1205. options = options || {};
  1206. if (attrs) {
  1207. let validationError;
  1208. options.error = (_, validation) => {
  1209. validationError = validation;
  1210. };
  1211. const success = this.set(attrs, options);
  1212. if (!success) {
  1213. return Promise.reject(validationError);
  1214. }
  1215. }
  1216. const saveOptions = {};
  1217. if (options.hasOwnProperty('useMasterKey')) {
  1218. saveOptions.useMasterKey = !!options.useMasterKey;
  1219. }
  1220. if (options.hasOwnProperty('sessionToken') && typeof options.sessionToken === 'string') {
  1221. saveOptions.sessionToken = options.sessionToken;
  1222. }
  1223. if (options.hasOwnProperty('installationId') && typeof options.installationId === 'string') {
  1224. saveOptions.installationId = options.installationId;
  1225. }
  1226. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  1227. saveOptions.context = options.context;
  1228. }
  1229. const controller = _CoreManager.default.getObjectController();
  1230. const unsaved = options.cascadeSave !== false ? (0, _unsavedChildren.default)(this) : null;
  1231. return controller.save(unsaved, saveOptions).then(() => {
  1232. return controller.save(this, saveOptions);
  1233. });
  1234. }
  1235. /**
  1236. * Deletes this object from the server at some unspecified time in the future,
  1237. * even if Parse is currently inaccessible.
  1238. *
  1239. * Use this when you may not have a solid network connection,
  1240. * and don't need to know when the delete completes. If there is some problem with the object
  1241. * such that it can't be deleted, the request will be silently discarded.
  1242. *
  1243. * Delete instructions made with this method will be stored locally in an on-disk cache until they can be transmitted
  1244. * to Parse. They will be sent immediately if possible. Otherwise, they will be sent the next time a network connection
  1245. * is available. Delete requests will persist even after the app is closed, in which case they will be sent the
  1246. * next time the app is opened.
  1247. *
  1248. * @param {object} [options]
  1249. * Valid options are:<ul>
  1250. * <li>sessionToken: A valid session token, used for making a request on
  1251. * behalf of a specific user.
  1252. * <li>context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers.
  1253. * </ul>
  1254. * @returns {Promise} A promise that is fulfilled when the destroy
  1255. * completes.
  1256. */
  1257. async destroyEventually(options) {
  1258. try {
  1259. await this.destroy(options);
  1260. } catch (e) {
  1261. if (e.code === _ParseError.default.CONNECTION_FAILED) {
  1262. await _CoreManager.default.getEventuallyQueue().destroy(this, options);
  1263. _CoreManager.default.getEventuallyQueue().poll();
  1264. }
  1265. }
  1266. return this;
  1267. }
  1268. /**
  1269. * Destroy this model on the server if it was already persisted.
  1270. *
  1271. * @param {object} options
  1272. * Valid options are:<ul>
  1273. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1274. * be used for this request.
  1275. * <li>sessionToken: A valid session token, used for making a request on
  1276. * behalf of a specific user.
  1277. * <li>context: A dictionary that is accessible in Cloud Code `beforeDelete` and `afterDelete` triggers.
  1278. * </ul>
  1279. * @returns {Promise} A promise that is fulfilled when the destroy
  1280. * completes.
  1281. */
  1282. destroy(options) {
  1283. options = options || {};
  1284. const destroyOptions = {};
  1285. if (options.hasOwnProperty('useMasterKey')) {
  1286. destroyOptions.useMasterKey = options.useMasterKey;
  1287. }
  1288. if (options.hasOwnProperty('sessionToken')) {
  1289. destroyOptions.sessionToken = options.sessionToken;
  1290. }
  1291. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  1292. destroyOptions.context = options.context;
  1293. }
  1294. if (!this.id) {
  1295. return Promise.resolve();
  1296. }
  1297. return _CoreManager.default.getObjectController().destroy(this, destroyOptions);
  1298. }
  1299. /**
  1300. * Asynchronously stores the object and every object it points to in the local datastore,
  1301. * recursively, using a default pin name: _default.
  1302. *
  1303. * If those other objects have not been fetched from Parse, they will not be stored.
  1304. * However, if they have changed data, all the changes will be retained.
  1305. *
  1306. * <pre>
  1307. * await object.pin();
  1308. * </pre>
  1309. *
  1310. * To retrieve object:
  1311. * <code>query.fromLocalDatastore()</code> or <code>query.fromPin()</code>
  1312. *
  1313. * @returns {Promise} A promise that is fulfilled when the pin completes.
  1314. */
  1315. pin() {
  1316. return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
  1317. }
  1318. /**
  1319. * Asynchronously removes the object and every object it points to in the local datastore,
  1320. * recursively, using a default pin name: _default.
  1321. *
  1322. * <pre>
  1323. * await object.unPin();
  1324. * </pre>
  1325. *
  1326. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  1327. */
  1328. unPin() {
  1329. return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
  1330. }
  1331. /**
  1332. * Asynchronously returns if the object is pinned
  1333. *
  1334. * <pre>
  1335. * const isPinned = await object.isPinned();
  1336. * </pre>
  1337. *
  1338. * @returns {Promise<boolean>} A boolean promise that is fulfilled if object is pinned.
  1339. */
  1340. async isPinned() {
  1341. const localDatastore = _CoreManager.default.getLocalDatastore();
  1342. if (!localDatastore.isEnabled) {
  1343. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  1344. }
  1345. const objectKey = localDatastore.getKeyForObject(this);
  1346. const pin = await localDatastore.fromPinWithName(objectKey);
  1347. return pin.length > 0;
  1348. }
  1349. /**
  1350. * Asynchronously stores the objects and every object they point to in the local datastore, recursively.
  1351. *
  1352. * If those other objects have not been fetched from Parse, they will not be stored.
  1353. * However, if they have changed data, all the changes will be retained.
  1354. *
  1355. * <pre>
  1356. * await object.pinWithName(name);
  1357. * </pre>
  1358. *
  1359. * To retrieve object:
  1360. * <code>query.fromLocalDatastore()</code> or <code>query.fromPinWithName(name)</code>
  1361. *
  1362. * @param {string} name Name of Pin.
  1363. * @returns {Promise} A promise that is fulfilled when the pin completes.
  1364. */
  1365. pinWithName(name) {
  1366. return ParseObject.pinAllWithName(name, [this]);
  1367. }
  1368. /**
  1369. * Asynchronously removes the object and every object it points to in the local datastore, recursively.
  1370. *
  1371. * <pre>
  1372. * await object.unPinWithName(name);
  1373. * </pre>
  1374. *
  1375. * @param {string} name Name of Pin.
  1376. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  1377. */
  1378. unPinWithName(name) {
  1379. return ParseObject.unPinAllWithName(name, [this]);
  1380. }
  1381. /**
  1382. * Asynchronously loads data from the local datastore into this object.
  1383. *
  1384. * <pre>
  1385. * await object.fetchFromLocalDatastore();
  1386. * </pre>
  1387. *
  1388. * You can create an unfetched pointer with <code>Parse.Object.createWithoutData()</code>
  1389. * and then call <code>fetchFromLocalDatastore()</code> on it.
  1390. *
  1391. * @returns {Promise} A promise that is fulfilled when the fetch completes.
  1392. */
  1393. async fetchFromLocalDatastore() {
  1394. const localDatastore = _CoreManager.default.getLocalDatastore();
  1395. if (!localDatastore.isEnabled) {
  1396. throw new Error('Parse.enableLocalDatastore() must be called first');
  1397. }
  1398. const objectKey = localDatastore.getKeyForObject(this);
  1399. const pinned = await localDatastore._serializeObject(objectKey);
  1400. if (!pinned) {
  1401. throw new Error('Cannot fetch an unsaved ParseObject');
  1402. }
  1403. const result = ParseObject.fromJSON(pinned);
  1404. this._finishFetch(result.toJSON());
  1405. return this;
  1406. }
  1407. /* Static methods */
  1408. static _clearAllState() {
  1409. const stateController = _CoreManager.default.getObjectStateController();
  1410. stateController.clearAllState();
  1411. }
  1412. /**
  1413. * Fetches the given list of Parse.Object.
  1414. * If any error is encountered, stops and calls the error handler.
  1415. *
  1416. * <pre>
  1417. * Parse.Object.fetchAll([object1, object2, ...])
  1418. * .then((list) => {
  1419. * // All the objects were fetched.
  1420. * }, (error) => {
  1421. * // An error occurred while fetching one of the objects.
  1422. * });
  1423. * </pre>
  1424. *
  1425. * @param {Array} list A list of <code>Parse.Object</code>.
  1426. * @param {object} options
  1427. * Valid options are:<ul>
  1428. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1429. * be used for this request.
  1430. * <li>sessionToken: A valid session token, used for making a request on
  1431. * behalf of a specific user.
  1432. * <li>include: The name(s) of the key(s) to include. Can be a string, an array of strings,
  1433. * or an array of array of strings.
  1434. * </ul>
  1435. * @static
  1436. * @returns {Parse.Object[]}
  1437. */
  1438. static fetchAll(list, options = {}) {
  1439. const queryOptions = {};
  1440. if (options.hasOwnProperty('useMasterKey')) {
  1441. queryOptions.useMasterKey = options.useMasterKey;
  1442. }
  1443. if (options.hasOwnProperty('sessionToken')) {
  1444. queryOptions.sessionToken = options.sessionToken;
  1445. }
  1446. if (options.hasOwnProperty('include')) {
  1447. queryOptions.include = ParseObject.handleIncludeOptions(options);
  1448. }
  1449. return _CoreManager.default.getObjectController().fetch(list, true, queryOptions);
  1450. }
  1451. /**
  1452. * Fetches the given list of Parse.Object.
  1453. *
  1454. * Includes nested Parse.Objects for the provided key. You can use dot
  1455. * notation to specify which fields in the included object are also fetched.
  1456. *
  1457. * If any error is encountered, stops and calls the error handler.
  1458. *
  1459. * <pre>
  1460. * Parse.Object.fetchAllWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
  1461. * .then((list) => {
  1462. * // All the objects were fetched.
  1463. * }, (error) => {
  1464. * // An error occurred while fetching one of the objects.
  1465. * });
  1466. * </pre>
  1467. *
  1468. * @param {Array} list A list of <code>Parse.Object</code>.
  1469. * @param {string | Array<string | Array<string>>} keys The name(s) of the key(s) to include.
  1470. * @param {object} options
  1471. * Valid options are:<ul>
  1472. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1473. * be used for this request.
  1474. * <li>sessionToken: A valid session token, used for making a request on
  1475. * behalf of a specific user.
  1476. * </ul>
  1477. * @static
  1478. * @returns {Parse.Object[]}
  1479. */
  1480. static fetchAllWithInclude(list, keys, options) {
  1481. options = options || {};
  1482. options.include = keys;
  1483. return ParseObject.fetchAll(list, options);
  1484. }
  1485. /**
  1486. * Fetches the given list of Parse.Object if needed.
  1487. * If any error is encountered, stops and calls the error handler.
  1488. *
  1489. * Includes nested Parse.Objects for the provided key. You can use dot
  1490. * notation to specify which fields in the included object are also fetched.
  1491. *
  1492. * If any error is encountered, stops and calls the error handler.
  1493. *
  1494. * <pre>
  1495. * Parse.Object.fetchAllIfNeededWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
  1496. * .then((list) => {
  1497. * // All the objects were fetched.
  1498. * }, (error) => {
  1499. * // An error occurred while fetching one of the objects.
  1500. * });
  1501. * </pre>
  1502. *
  1503. * @param {Array} list A list of <code>Parse.Object</code>.
  1504. * @param {string | Array<string | Array<string>>} keys The name(s) of the key(s) to include.
  1505. * @param {object} options
  1506. * Valid options are:<ul>
  1507. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
  1508. * be used for this request.
  1509. * <li>sessionToken: A valid session token, used for making a request on
  1510. * behalf of a specific user.
  1511. * </ul>
  1512. * @static
  1513. * @returns {Parse.Object[]}
  1514. */
  1515. static fetchAllIfNeededWithInclude(list, keys, options) {
  1516. options = options || {};
  1517. options.include = keys;
  1518. return ParseObject.fetchAllIfNeeded(list, options);
  1519. }
  1520. /**
  1521. * Fetches the given list of Parse.Object if needed.
  1522. * If any error is encountered, stops and calls the error handler.
  1523. *
  1524. * <pre>
  1525. * Parse.Object.fetchAllIfNeeded([object1, ...])
  1526. * .then((list) => {
  1527. * // Objects were fetched and updated.
  1528. * }, (error) => {
  1529. * // An error occurred while fetching one of the objects.
  1530. * });
  1531. * </pre>
  1532. *
  1533. * @param {Array} list A list of <code>Parse.Object</code>.
  1534. * @param {object} options
  1535. * @static
  1536. * @returns {Parse.Object[]}
  1537. */
  1538. static fetchAllIfNeeded(list, options) {
  1539. options = options || {};
  1540. const queryOptions = {};
  1541. if (options.hasOwnProperty('useMasterKey')) {
  1542. queryOptions.useMasterKey = options.useMasterKey;
  1543. }
  1544. if (options.hasOwnProperty('sessionToken')) {
  1545. queryOptions.sessionToken = options.sessionToken;
  1546. }
  1547. if (options.hasOwnProperty('include')) {
  1548. queryOptions.include = ParseObject.handleIncludeOptions(options);
  1549. }
  1550. return _CoreManager.default.getObjectController().fetch(list, false, queryOptions);
  1551. }
  1552. static handleIncludeOptions(options) {
  1553. let include = [];
  1554. if (Array.isArray(options.include)) {
  1555. options.include.forEach(key => {
  1556. if (Array.isArray(key)) {
  1557. include = include.concat(key);
  1558. } else {
  1559. include.push(key);
  1560. }
  1561. });
  1562. } else {
  1563. include.push(options.include);
  1564. }
  1565. return include;
  1566. }
  1567. /**
  1568. * Destroy the given list of models on the server if it was already persisted.
  1569. *
  1570. * <p>Unlike saveAll, if an error occurs while deleting an individual model,
  1571. * this method will continue trying to delete the rest of the models if
  1572. * possible, except in the case of a fatal error like a connection error.
  1573. *
  1574. * <p>In particular, the Parse.Error object returned in the case of error may
  1575. * be one of two types:
  1576. *
  1577. * <ul>
  1578. * <li>A Parse.Error.AGGREGATE_ERROR. This object's "errors" property is an
  1579. * array of other Parse.Error objects. Each error object in this array
  1580. * has an "object" property that references the object that could not be
  1581. * deleted (for instance, because that object could not be found).</li>
  1582. * <li>A non-aggregate Parse.Error. This indicates a serious error that
  1583. * caused the delete operation to be aborted partway through (for
  1584. * instance, a connection failure in the middle of the delete).</li>
  1585. * </ul>
  1586. *
  1587. * <pre>
  1588. * Parse.Object.destroyAll([object1, object2, ...])
  1589. * .then((list) => {
  1590. * // All the objects were deleted.
  1591. * }, (error) => {
  1592. * // An error occurred while deleting one or more of the objects.
  1593. * // If this is an aggregate error, then we can inspect each error
  1594. * // object individually to determine the reason why a particular
  1595. * // object was not deleted.
  1596. * if (error.code === Parse.Error.AGGREGATE_ERROR) {
  1597. * for (var i = 0; i < error.errors.length; i++) {
  1598. * console.log("Couldn't delete " + error.errors[i].object.id +
  1599. * "due to " + error.errors[i].message);
  1600. * }
  1601. * } else {
  1602. * console.log("Delete aborted because of " + error.message);
  1603. * }
  1604. * });
  1605. * </pre>
  1606. *
  1607. * @param {Array} list A list of <code>Parse.Object</code>.
  1608. * @param {object} options
  1609. * @static
  1610. * @returns {Promise} A promise that is fulfilled when the destroyAll
  1611. * completes.
  1612. */
  1613. static destroyAll(list, options = {}) {
  1614. const destroyOptions = {};
  1615. if (options.hasOwnProperty('useMasterKey')) {
  1616. destroyOptions.useMasterKey = options.useMasterKey;
  1617. }
  1618. if (options.hasOwnProperty('sessionToken')) {
  1619. destroyOptions.sessionToken = options.sessionToken;
  1620. }
  1621. if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
  1622. destroyOptions.batchSize = options.batchSize;
  1623. }
  1624. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  1625. destroyOptions.context = options.context;
  1626. }
  1627. return _CoreManager.default.getObjectController().destroy(list, destroyOptions);
  1628. }
  1629. /**
  1630. * Saves the given list of Parse.Object.
  1631. * If any error is encountered, stops and calls the error handler.
  1632. *
  1633. * <pre>
  1634. * Parse.Object.saveAll([object1, object2, ...])
  1635. * .then((list) => {
  1636. * // All the objects were saved.
  1637. * }, (error) => {
  1638. * // An error occurred while saving one of the objects.
  1639. * });
  1640. * </pre>
  1641. *
  1642. * @param {Array} list A list of <code>Parse.Object</code>.
  1643. * @param {object} options
  1644. * @static
  1645. * @returns {Parse.Object[]}
  1646. */
  1647. static saveAll(list, options = {}) {
  1648. const saveOptions = {};
  1649. if (options.hasOwnProperty('useMasterKey')) {
  1650. saveOptions.useMasterKey = options.useMasterKey;
  1651. }
  1652. if (options.hasOwnProperty('sessionToken')) {
  1653. saveOptions.sessionToken = options.sessionToken;
  1654. }
  1655. if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
  1656. saveOptions.batchSize = options.batchSize;
  1657. }
  1658. if (options.hasOwnProperty('context') && typeof options.context === 'object') {
  1659. saveOptions.context = options.context;
  1660. }
  1661. return _CoreManager.default.getObjectController().save(list, saveOptions);
  1662. }
  1663. /**
  1664. * Creates a reference to a subclass of Parse.Object with the given id. This
  1665. * does not exist on Parse.Object, only on subclasses.
  1666. *
  1667. * <p>A shortcut for: <pre>
  1668. * var Foo = Parse.Object.extend("Foo");
  1669. * var pointerToFoo = new Foo();
  1670. * pointerToFoo.id = "myObjectId";
  1671. * </pre>
  1672. *
  1673. * @param {string} id The ID of the object to create a reference to.
  1674. * @static
  1675. * @returns {Parse.Object} A Parse.Object reference.
  1676. */
  1677. static createWithoutData(id) {
  1678. const obj = new this();
  1679. obj.id = id;
  1680. return obj;
  1681. }
  1682. /**
  1683. * Creates a new instance of a Parse Object from a JSON representation.
  1684. *
  1685. * @param {object} json The JSON map of the Object's data
  1686. * @param {boolean} override In single instance mode, all old server data
  1687. * is overwritten if this is set to true
  1688. * @param {boolean} dirty Whether the Parse.Object should set JSON keys to dirty
  1689. * @static
  1690. * @returns {Parse.Object} A Parse.Object reference
  1691. */
  1692. static fromJSON(json, override, dirty) {
  1693. if (!json.className) {
  1694. throw new Error('Cannot create an object without a className');
  1695. }
  1696. const constructor = classMap[json.className];
  1697. const o = constructor ? new constructor(json.className) : new ParseObject(json.className);
  1698. const otherAttributes = {};
  1699. for (const attr in json) {
  1700. if (attr !== 'className' && attr !== '__type') {
  1701. otherAttributes[attr] = json[attr];
  1702. if (dirty) {
  1703. o.set(attr, json[attr]);
  1704. }
  1705. }
  1706. }
  1707. if (override) {
  1708. // id needs to be set before clearServerData can work
  1709. if (otherAttributes.objectId) {
  1710. o.id = otherAttributes.objectId;
  1711. }
  1712. let preserved = null;
  1713. if (typeof o._preserveFieldsOnFetch === 'function') {
  1714. preserved = o._preserveFieldsOnFetch();
  1715. }
  1716. o._clearServerData();
  1717. if (preserved) {
  1718. o._finishFetch(preserved);
  1719. }
  1720. }
  1721. o._finishFetch(otherAttributes);
  1722. if (json.objectId) {
  1723. o._setExisted(true);
  1724. }
  1725. return o;
  1726. }
  1727. /**
  1728. * Registers a subclass of Parse.Object with a specific class name.
  1729. * When objects of that class are retrieved from a query, they will be
  1730. * instantiated with this subclass.
  1731. * This is only necessary when using ES6 subclassing.
  1732. *
  1733. * @param {string} className The class name of the subclass
  1734. * @param {Function} constructor The subclass
  1735. */
  1736. static registerSubclass(className, constructor) {
  1737. if (typeof className !== 'string') {
  1738. throw new TypeError('The first argument must be a valid class name.');
  1739. }
  1740. if (typeof constructor === 'undefined') {
  1741. throw new TypeError('You must supply a subclass constructor.');
  1742. }
  1743. if (typeof constructor !== 'function') {
  1744. throw new TypeError('You must register the subclass constructor. ' + 'Did you attempt to register an instance of the subclass?');
  1745. }
  1746. classMap[className] = constructor;
  1747. if (!constructor.className) {
  1748. constructor.className = className;
  1749. }
  1750. }
  1751. /**
  1752. * Unegisters a subclass of Parse.Object with a specific class name.
  1753. *
  1754. * @param {string} className The class name of the subclass
  1755. */
  1756. static unregisterSubclass(className) {
  1757. if (typeof className !== 'string') {
  1758. throw new TypeError('The first argument must be a valid class name.');
  1759. }
  1760. delete classMap[className];
  1761. }
  1762. /**
  1763. * Creates a new subclass of Parse.Object for the given Parse class name.
  1764. *
  1765. * <p>Every extension of a Parse class will inherit from the most recent
  1766. * previous extension of that class. When a Parse.Object is automatically
  1767. * created by parsing JSON, it will use the most recent extension of that
  1768. * class.</p>
  1769. *
  1770. * <p>You should call either:<pre>
  1771. * var MyClass = Parse.Object.extend("MyClass", {
  1772. * <i>Instance methods</i>,
  1773. * initialize: function(attrs, options) {
  1774. * this.someInstanceProperty = [],
  1775. * <i>Other instance properties</i>
  1776. * }
  1777. * }, {
  1778. * <i>Class properties</i>
  1779. * });</pre>
  1780. * or, for Backbone compatibility:<pre>
  1781. * var MyClass = Parse.Object.extend({
  1782. * className: "MyClass",
  1783. * <i>Instance methods</i>,
  1784. * initialize: function(attrs, options) {
  1785. * this.someInstanceProperty = [],
  1786. * <i>Other instance properties</i>
  1787. * }
  1788. * }, {
  1789. * <i>Class properties</i>
  1790. * });</pre></p>
  1791. *
  1792. * @param {string} className The name of the Parse class backing this model.
  1793. * @param {object} [protoProps] Instance properties to add to instances of the
  1794. * class returned from this method.
  1795. * @param {object} [classProps] Class properties to add the class returned from
  1796. * this method.
  1797. * @returns {Parse.Object} A new subclass of Parse.Object.
  1798. */
  1799. static extend(className, protoProps, classProps) {
  1800. if (typeof className !== 'string') {
  1801. if (className && typeof className.className === 'string') {
  1802. return ParseObject.extend(className.className, className, protoProps);
  1803. } else {
  1804. throw new Error("Parse.Object.extend's first argument should be the className.");
  1805. }
  1806. }
  1807. let adjustedClassName = className;
  1808. if (adjustedClassName === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
  1809. adjustedClassName = '_User';
  1810. }
  1811. let parentProto = ParseObject.prototype;
  1812. if (this.hasOwnProperty('__super__') && this.__super__) {
  1813. parentProto = this.prototype;
  1814. }
  1815. let ParseObjectSubclass = function (attributes, options) {
  1816. this.className = adjustedClassName;
  1817. this._objCount = objectCount++;
  1818. // Enable legacy initializers
  1819. if (typeof this.initialize === 'function') {
  1820. this.initialize.apply(this, arguments);
  1821. }
  1822. if (this._initializers) {
  1823. for (const initializer of this._initializers) {
  1824. initializer.apply(this, arguments);
  1825. }
  1826. }
  1827. if (attributes && typeof attributes === 'object') {
  1828. if (!this.set(attributes || {}, options)) {
  1829. throw new Error("Can't create an invalid Parse Object");
  1830. }
  1831. }
  1832. };
  1833. if (classMap[adjustedClassName]) {
  1834. ParseObjectSubclass = classMap[adjustedClassName];
  1835. } else {
  1836. ParseObjectSubclass.extend = function (name, protoProps, classProps) {
  1837. if (typeof name === 'string') {
  1838. return ParseObject.extend.call(ParseObjectSubclass, name, protoProps, classProps);
  1839. }
  1840. return ParseObject.extend.call(ParseObjectSubclass, adjustedClassName, name, protoProps);
  1841. };
  1842. ParseObjectSubclass.createWithoutData = ParseObject.createWithoutData;
  1843. ParseObjectSubclass.className = adjustedClassName;
  1844. ParseObjectSubclass.__super__ = parentProto;
  1845. ParseObjectSubclass.prototype = Object.create(parentProto, {
  1846. constructor: {
  1847. value: ParseObjectSubclass,
  1848. enumerable: false,
  1849. writable: true,
  1850. configurable: true
  1851. }
  1852. });
  1853. }
  1854. if (protoProps) {
  1855. for (const prop in protoProps) {
  1856. if (prop === 'initialize') {
  1857. Object.defineProperty(ParseObjectSubclass.prototype, '_initializers', {
  1858. value: [...(ParseObjectSubclass.prototype._initializers || []), protoProps[prop]],
  1859. enumerable: false,
  1860. writable: true,
  1861. configurable: true
  1862. });
  1863. continue;
  1864. }
  1865. if (prop !== 'className') {
  1866. Object.defineProperty(ParseObjectSubclass.prototype, prop, {
  1867. value: protoProps[prop],
  1868. enumerable: false,
  1869. writable: true,
  1870. configurable: true
  1871. });
  1872. }
  1873. }
  1874. }
  1875. if (classProps) {
  1876. for (const prop in classProps) {
  1877. if (prop !== 'className') {
  1878. Object.defineProperty(ParseObjectSubclass, prop, {
  1879. value: classProps[prop],
  1880. enumerable: false,
  1881. writable: true,
  1882. configurable: true
  1883. });
  1884. }
  1885. }
  1886. }
  1887. classMap[adjustedClassName] = ParseObjectSubclass;
  1888. return ParseObjectSubclass;
  1889. }
  1890. /**
  1891. * Enable single instance objects, where any local objects with the same Id
  1892. * share the same attributes, and stay synchronized with each other.
  1893. * This is disabled by default in server environments, since it can lead to
  1894. * security issues.
  1895. *
  1896. * @static
  1897. */
  1898. static enableSingleInstance() {
  1899. singleInstance = true;
  1900. _CoreManager.default.setObjectStateController(SingleInstanceStateController);
  1901. }
  1902. /**
  1903. * Disable single instance objects, where any local objects with the same Id
  1904. * share the same attributes, and stay synchronized with each other.
  1905. * When disabled, you can have two instances of the same object in memory
  1906. * without them sharing attributes.
  1907. *
  1908. * @static
  1909. */
  1910. static disableSingleInstance() {
  1911. singleInstance = false;
  1912. _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
  1913. }
  1914. /**
  1915. * Asynchronously stores the objects and every object they point to in the local datastore,
  1916. * recursively, using a default pin name: _default.
  1917. *
  1918. * If those other objects have not been fetched from Parse, they will not be stored.
  1919. * However, if they have changed data, all the changes will be retained.
  1920. *
  1921. * <pre>
  1922. * await Parse.Object.pinAll([...]);
  1923. * </pre>
  1924. *
  1925. * To retrieve object:
  1926. * <code>query.fromLocalDatastore()</code> or <code>query.fromPin()</code>
  1927. *
  1928. * @param {Array} objects A list of <code>Parse.Object</code>.
  1929. * @returns {Promise} A promise that is fulfilled when the pin completes.
  1930. * @static
  1931. */
  1932. static pinAll(objects) {
  1933. const localDatastore = _CoreManager.default.getLocalDatastore();
  1934. if (!localDatastore.isEnabled) {
  1935. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  1936. }
  1937. return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
  1938. }
  1939. /**
  1940. * Asynchronously stores the objects and every object they point to in the local datastore, recursively.
  1941. *
  1942. * If those other objects have not been fetched from Parse, they will not be stored.
  1943. * However, if they have changed data, all the changes will be retained.
  1944. *
  1945. * <pre>
  1946. * await Parse.Object.pinAllWithName(name, [obj1, obj2, ...]);
  1947. * </pre>
  1948. *
  1949. * To retrieve object:
  1950. * <code>query.fromLocalDatastore()</code> or <code>query.fromPinWithName(name)</code>
  1951. *
  1952. * @param {string} name Name of Pin.
  1953. * @param {Array} objects A list of <code>Parse.Object</code>.
  1954. * @returns {Promise} A promise that is fulfilled when the pin completes.
  1955. * @static
  1956. */
  1957. static pinAllWithName(name, objects) {
  1958. const localDatastore = _CoreManager.default.getLocalDatastore();
  1959. if (!localDatastore.isEnabled) {
  1960. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  1961. }
  1962. return localDatastore._handlePinAllWithName(name, objects);
  1963. }
  1964. /**
  1965. * Asynchronously removes the objects and every object they point to in the local datastore,
  1966. * recursively, using a default pin name: _default.
  1967. *
  1968. * <pre>
  1969. * await Parse.Object.unPinAll([...]);
  1970. * </pre>
  1971. *
  1972. * @param {Array} objects A list of <code>Parse.Object</code>.
  1973. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  1974. * @static
  1975. */
  1976. static unPinAll(objects) {
  1977. const localDatastore = _CoreManager.default.getLocalDatastore();
  1978. if (!localDatastore.isEnabled) {
  1979. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  1980. }
  1981. return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
  1982. }
  1983. /**
  1984. * Asynchronously removes the objects and every object they point to in the local datastore, recursively.
  1985. *
  1986. * <pre>
  1987. * await Parse.Object.unPinAllWithName(name, [obj1, obj2, ...]);
  1988. * </pre>
  1989. *
  1990. * @param {string} name Name of Pin.
  1991. * @param {Array} objects A list of <code>Parse.Object</code>.
  1992. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  1993. * @static
  1994. */
  1995. static unPinAllWithName(name, objects) {
  1996. const localDatastore = _CoreManager.default.getLocalDatastore();
  1997. if (!localDatastore.isEnabled) {
  1998. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  1999. }
  2000. return localDatastore._handleUnPinAllWithName(name, objects);
  2001. }
  2002. /**
  2003. * Asynchronously removes all objects in the local datastore using a default pin name: _default.
  2004. *
  2005. * <pre>
  2006. * await Parse.Object.unPinAllObjects();
  2007. * </pre>
  2008. *
  2009. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  2010. * @static
  2011. */
  2012. static unPinAllObjects() {
  2013. const localDatastore = _CoreManager.default.getLocalDatastore();
  2014. if (!localDatastore.isEnabled) {
  2015. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  2016. }
  2017. return localDatastore.unPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
  2018. }
  2019. /**
  2020. * Asynchronously removes all objects with the specified pin name.
  2021. * Deletes the pin name also.
  2022. *
  2023. * <pre>
  2024. * await Parse.Object.unPinAllObjectsWithName(name);
  2025. * </pre>
  2026. *
  2027. * @param {string} name Name of Pin.
  2028. * @returns {Promise} A promise that is fulfilled when the unPin completes.
  2029. * @static
  2030. */
  2031. static unPinAllObjectsWithName(name) {
  2032. const localDatastore = _CoreManager.default.getLocalDatastore();
  2033. if (!localDatastore.isEnabled) {
  2034. return Promise.reject('Parse.enableLocalDatastore() must be called first');
  2035. }
  2036. return localDatastore.unPinWithName(_LocalDatastoreUtils.PIN_PREFIX + name);
  2037. }
  2038. }
  2039. const DefaultController = {
  2040. fetch(target, forceFetch, options) {
  2041. const localDatastore = _CoreManager.default.getLocalDatastore();
  2042. if (Array.isArray(target)) {
  2043. if (target.length < 1) {
  2044. return Promise.resolve([]);
  2045. }
  2046. const objs = [];
  2047. const ids = [];
  2048. let className = null;
  2049. const results = [];
  2050. let error = null;
  2051. target.forEach(el => {
  2052. if (error) {
  2053. return;
  2054. }
  2055. if (!className) {
  2056. className = el.className;
  2057. }
  2058. if (className !== el.className) {
  2059. error = new _ParseError.default(_ParseError.default.INVALID_CLASS_NAME, 'All objects should be of the same class');
  2060. }
  2061. if (!el.id) {
  2062. error = new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'All objects must have an ID');
  2063. }
  2064. if (forceFetch || !el.isDataAvailable()) {
  2065. ids.push(el.id);
  2066. objs.push(el);
  2067. }
  2068. results.push(el);
  2069. });
  2070. if (error) {
  2071. return Promise.reject(error);
  2072. }
  2073. const ParseQuery = _CoreManager.default.getParseQuery();
  2074. const query = new ParseQuery(className);
  2075. query.containedIn('objectId', ids);
  2076. if (options && options.include) {
  2077. query.include(options.include);
  2078. }
  2079. query._limit = ids.length;
  2080. return query.find(options).then(async objects => {
  2081. const idMap = {};
  2082. objects.forEach(o => {
  2083. idMap[o.id] = o;
  2084. });
  2085. for (let i = 0; i < objs.length; i++) {
  2086. const obj = objs[i];
  2087. if (!obj || !obj.id || !idMap[obj.id]) {
  2088. if (forceFetch) {
  2089. return Promise.reject(new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'All objects must exist on the server.'));
  2090. }
  2091. }
  2092. }
  2093. if (!singleInstance) {
  2094. // If single instance objects are disabled, we need to replace the
  2095. for (let i = 0; i < results.length; i++) {
  2096. const obj = results[i];
  2097. if (obj && obj.id && idMap[obj.id]) {
  2098. const id = obj.id;
  2099. obj._finishFetch(idMap[id].toJSON());
  2100. results[i] = idMap[id];
  2101. }
  2102. }
  2103. }
  2104. for (const object of results) {
  2105. await localDatastore._updateObjectIfPinned(object);
  2106. }
  2107. return Promise.resolve(results);
  2108. });
  2109. } else if (target instanceof ParseObject) {
  2110. if (!target.id) {
  2111. return Promise.reject(new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'Object does not have an ID'));
  2112. }
  2113. const RESTController = _CoreManager.default.getRESTController();
  2114. const params = {};
  2115. if (options && options.include) {
  2116. params.include = options.include.join();
  2117. }
  2118. return RESTController.request('GET', 'classes/' + target.className + '/' + target._getId(), params, options).then(async response => {
  2119. target._clearPendingOps();
  2120. target._clearServerData();
  2121. target._finishFetch(response);
  2122. await localDatastore._updateObjectIfPinned(target);
  2123. return target;
  2124. });
  2125. }
  2126. return Promise.resolve(undefined);
  2127. },
  2128. async destroy(target, options) {
  2129. const batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
  2130. const localDatastore = _CoreManager.default.getLocalDatastore();
  2131. const RESTController = _CoreManager.default.getRESTController();
  2132. if (Array.isArray(target)) {
  2133. if (target.length < 1) {
  2134. return Promise.resolve([]);
  2135. }
  2136. const batches = [[]];
  2137. target.forEach(obj => {
  2138. if (!obj.id) {
  2139. return;
  2140. }
  2141. batches[batches.length - 1].push(obj);
  2142. if (batches[batches.length - 1].length >= batchSize) {
  2143. batches.push([]);
  2144. }
  2145. });
  2146. if (batches[batches.length - 1].length === 0) {
  2147. // If the last batch is empty, remove it
  2148. batches.pop();
  2149. }
  2150. let deleteCompleted = Promise.resolve();
  2151. const errors = [];
  2152. batches.forEach(batch => {
  2153. deleteCompleted = deleteCompleted.then(() => {
  2154. return RESTController.request('POST', 'batch', {
  2155. requests: batch.map(obj => {
  2156. return {
  2157. method: 'DELETE',
  2158. path: getServerUrlPath() + 'classes/' + obj.className + '/' + obj._getId(),
  2159. body: {}
  2160. };
  2161. })
  2162. }, options).then(results => {
  2163. for (let i = 0; i < results.length; i++) {
  2164. if (results[i] && results[i].hasOwnProperty('error')) {
  2165. const err = new _ParseError.default(results[i].error.code, results[i].error.error);
  2166. err.object = batch[i];
  2167. errors.push(err);
  2168. }
  2169. }
  2170. });
  2171. });
  2172. });
  2173. return deleteCompleted.then(async () => {
  2174. if (errors.length) {
  2175. const aggregate = new _ParseError.default(_ParseError.default.AGGREGATE_ERROR);
  2176. aggregate.errors = errors;
  2177. return Promise.reject(aggregate);
  2178. }
  2179. for (const object of target) {
  2180. await localDatastore._destroyObjectIfPinned(object);
  2181. }
  2182. return Promise.resolve(target);
  2183. });
  2184. } else if (target instanceof ParseObject) {
  2185. return RESTController.request('DELETE', 'classes/' + target.className + '/' + target._getId(), {}, options).then(async () => {
  2186. await localDatastore._destroyObjectIfPinned(target);
  2187. return Promise.resolve(target);
  2188. });
  2189. }
  2190. return Promise.resolve(target);
  2191. },
  2192. save(target, options) {
  2193. const batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
  2194. const localDatastore = _CoreManager.default.getLocalDatastore();
  2195. const mapIdForPin = {};
  2196. const RESTController = _CoreManager.default.getRESTController();
  2197. const stateController = _CoreManager.default.getObjectStateController();
  2198. const allowCustomObjectId = _CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID');
  2199. options = options || {};
  2200. options.returnStatus = options.returnStatus || true;
  2201. if (Array.isArray(target)) {
  2202. if (target.length < 1) {
  2203. return Promise.resolve([]);
  2204. }
  2205. let unsaved = target.concat();
  2206. for (let i = 0; i < target.length; i++) {
  2207. const target_i = target[i];
  2208. if (target_i instanceof ParseObject) {
  2209. unsaved = unsaved.concat((0, _unsavedChildren.default)(target_i, true));
  2210. }
  2211. }
  2212. unsaved = (0, _unique.default)(unsaved);
  2213. const filesSaved = [];
  2214. let pending = [];
  2215. unsaved.forEach(el => {
  2216. if (el instanceof _ParseFile.default) {
  2217. filesSaved.push(el.save(options));
  2218. } else if (el instanceof ParseObject) {
  2219. pending.push(el);
  2220. }
  2221. });
  2222. return Promise.all(filesSaved).then(() => {
  2223. let objectError = null;
  2224. return (0, _promiseUtils.continueWhile)(() => {
  2225. return pending.length > 0;
  2226. }, () => {
  2227. const batch = [];
  2228. const nextPending = [];
  2229. pending.forEach(el => {
  2230. if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(el, 'id') && !el.id) {
  2231. throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null');
  2232. }
  2233. if (batch.length < batchSize && (0, _canBeSerialized.default)(el)) {
  2234. batch.push(el);
  2235. } else {
  2236. nextPending.push(el);
  2237. }
  2238. });
  2239. pending = nextPending;
  2240. if (batch.length < 1) {
  2241. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Tried to save a batch with a cycle.'));
  2242. }
  2243. // Queue up tasks for each object in the batch.
  2244. // When every task is ready, the API request will execute
  2245. const batchReturned = (0, _promiseUtils.resolvingPromise)();
  2246. const batchReady = [];
  2247. const batchTasks = [];
  2248. batch.forEach((obj, index) => {
  2249. const ready = (0, _promiseUtils.resolvingPromise)();
  2250. batchReady.push(ready);
  2251. stateController.pushPendingState(obj._getStateIdentifier());
  2252. batchTasks.push(stateController.enqueueTask(obj._getStateIdentifier(), function () {
  2253. ready.resolve();
  2254. return batchReturned.then(responses => {
  2255. if (responses[index].hasOwnProperty('success')) {
  2256. const objectId = responses[index].success.objectId;
  2257. const status = responses[index]._status;
  2258. delete responses[index]._status;
  2259. delete responses[index]._headers;
  2260. delete responses[index]._xhr;
  2261. mapIdForPin[objectId] = obj._localId;
  2262. obj._handleSaveResponse(responses[index].success, status);
  2263. } else {
  2264. if (!objectError && responses[index].hasOwnProperty('error')) {
  2265. const serverError = responses[index].error;
  2266. objectError = new _ParseError.default(serverError.code, serverError.error);
  2267. // Cancel the rest of the save
  2268. pending = [];
  2269. }
  2270. obj._handleSaveError();
  2271. }
  2272. });
  2273. }));
  2274. });
  2275. (0, _promiseUtils.when)(batchReady).then(() => {
  2276. // Kick off the batch request
  2277. return RESTController.request('POST', 'batch', {
  2278. requests: batch.map(obj => {
  2279. const params = obj._getSaveParams();
  2280. params.path = getServerUrlPath() + params.path;
  2281. return params;
  2282. })
  2283. }, options);
  2284. }).then(batchReturned.resolve, error => {
  2285. batchReturned.reject(new _ParseError.default(_ParseError.default.INCORRECT_TYPE, error.message));
  2286. });
  2287. return (0, _promiseUtils.when)(batchTasks);
  2288. }).then(async () => {
  2289. if (objectError) {
  2290. return Promise.reject(objectError);
  2291. }
  2292. for (const object of target) {
  2293. // Make sure that it is a ParseObject before updating it into the localDataStore
  2294. if (object instanceof ParseObject) {
  2295. await localDatastore._updateLocalIdForObject(mapIdForPin[object.id], object);
  2296. await localDatastore._updateObjectIfPinned(object);
  2297. }
  2298. }
  2299. return Promise.resolve(target);
  2300. });
  2301. });
  2302. } else if (target instanceof ParseObject) {
  2303. if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(target, 'id') && !target.id) {
  2304. throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null');
  2305. }
  2306. // generate _localId in case if cascadeSave=false
  2307. target._getId();
  2308. const localId = target._localId;
  2309. // copying target lets guarantee the pointer isn't modified elsewhere
  2310. const targetCopy = target;
  2311. const task = function () {
  2312. const params = targetCopy._getSaveParams();
  2313. return RESTController.request(params.method, params.path, params.body, options).then(response => {
  2314. const status = response._status;
  2315. delete response._status;
  2316. delete response._headers;
  2317. delete response._xhr;
  2318. targetCopy._handleSaveResponse(response, status);
  2319. }, error => {
  2320. targetCopy._handleSaveError();
  2321. return Promise.reject(error);
  2322. });
  2323. };
  2324. stateController.pushPendingState(target._getStateIdentifier());
  2325. return stateController.enqueueTask(target._getStateIdentifier(), task).then(async () => {
  2326. await localDatastore._updateLocalIdForObject(localId, target);
  2327. await localDatastore._updateObjectIfPinned(target);
  2328. return target;
  2329. }, error => {
  2330. return Promise.reject(error);
  2331. });
  2332. }
  2333. return Promise.resolve(undefined);
  2334. }
  2335. };
  2336. _CoreManager.default.setParseObject(ParseObject);
  2337. _CoreManager.default.setObjectController(DefaultController);
  2338. var _default = exports.default = ParseObject;