ParseObject.js 111 KB

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