ParseObject.js 75 KB

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