ParseObject.js 85 KB

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