ParseObject.js 107 KB

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