1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422 |
- "use strict";
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _CoreManager = _interopRequireDefault(require("./CoreManager"));
- var _canBeSerialized = _interopRequireDefault(require("./canBeSerialized"));
- var _decode = _interopRequireDefault(require("./decode"));
- var _encode = _interopRequireDefault(require("./encode"));
- var _escape = _interopRequireDefault(require("./escape"));
- var _ParseACL = _interopRequireDefault(require("./ParseACL"));
- var _parseDate = _interopRequireDefault(require("./parseDate"));
- var _ParseError = _interopRequireDefault(require("./ParseError"));
- var _ParseFile = _interopRequireDefault(require("./ParseFile"));
- var _promiseUtils = require("./promiseUtils");
- var _LocalDatastoreUtils = require("./LocalDatastoreUtils");
- var _uuid = _interopRequireDefault(require("./uuid"));
- var _ParseOp = require("./ParseOp");
- var _ParseRelation = _interopRequireDefault(require("./ParseRelation"));
- var SingleInstanceStateController = _interopRequireWildcard(require("./SingleInstanceStateController"));
- var _unique = _interopRequireDefault(require("./unique"));
- var UniqueInstanceStateController = _interopRequireWildcard(require("./UniqueInstanceStateController"));
- var _unsavedChildren = _interopRequireDefault(require("./unsavedChildren"));
- function _getRequireWildcardCache(e) {
- if ("function" != typeof WeakMap) return null;
- var r = new WeakMap(),
- t = new WeakMap();
- return (_getRequireWildcardCache = function (e) {
- return e ? t : r;
- })(e);
- }
- function _interopRequireWildcard(e, r) {
- if (!r && e && e.__esModule) return e;
- if (null === e || "object" != typeof e && "function" != typeof e) return {
- default: e
- };
- var t = _getRequireWildcardCache(r);
- if (t && t.has(e)) return t.get(e);
- var n = {
- __proto__: null
- },
- a = Object.defineProperty && Object.getOwnPropertyDescriptor;
- for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
- var i = a ? Object.getOwnPropertyDescriptor(e, u) : null;
- i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u];
- }
- return n.default = e, t && t.set(e, n), n;
- }
- function _interopRequireDefault(e) {
- return e && e.__esModule ? e : {
- default: e
- };
- }
- const classMap = {};
- let objectCount = 0;
- let singleInstance = !_CoreManager.default.get('IS_NODE');
- if (singleInstance) {
- _CoreManager.default.setObjectStateController(SingleInstanceStateController);
- } else {
- _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
- }
- function getServerUrlPath() {
- let serverUrl = _CoreManager.default.get('SERVER_URL');
- if (serverUrl[serverUrl.length - 1] !== '/') {
- serverUrl += '/';
- }
- const url = serverUrl.replace(/https?:\/\//, '');
- return url.substr(url.indexOf('/'));
- }
- class ParseObject {
-
- constructor(className, attributes, options) {
-
- if (typeof this.initialize === 'function') {
- this.initialize.apply(this, arguments);
- }
- let toSet = null;
- this._objCount = objectCount++;
- if (typeof className === 'string') {
- this.className = className;
- if (attributes && typeof attributes === 'object') {
- toSet = attributes;
- }
- } else if (className && typeof className === 'object') {
- this.className = className.className;
- toSet = {};
- for (const attr in className) {
- if (attr !== 'className') {
- toSet[attr] = className[attr];
- }
- }
- if (attributes && typeof attributes === 'object') {
- options = attributes;
- }
- }
- if (toSet && !this.set(toSet, options)) {
- throw new Error("Can't create an invalid Parse Object");
- }
- }
-
-
- get attributes() {
- const stateController = _CoreManager.default.getObjectStateController();
- return Object.freeze(stateController.estimateAttributes(this._getStateIdentifier()));
- }
-
- get createdAt() {
- return this._getServerData().createdAt;
- }
-
- get updatedAt() {
- return this._getServerData().updatedAt;
- }
-
-
- _getId() {
- if (typeof this.id === 'string') {
- return this.id;
- }
- if (typeof this._localId === 'string') {
- return this._localId;
- }
- const localId = 'local' + (0, _uuid.default)();
- this._localId = localId;
- return localId;
- }
-
- _getStateIdentifier() {
- if (singleInstance) {
- let id = this.id;
- if (!id) {
- id = this._getId();
- }
- return {
- id: id,
- className: this.className
- };
- } else {
- return this;
- }
- }
- _getServerData() {
- const stateController = _CoreManager.default.getObjectStateController();
- return stateController.getServerData(this._getStateIdentifier());
- }
- _clearServerData() {
- const serverData = this._getServerData();
- const unset = {};
- for (const attr in serverData) {
- unset[attr] = undefined;
- }
- const stateController = _CoreManager.default.getObjectStateController();
- stateController.setServerData(this._getStateIdentifier(), unset);
- }
- _getPendingOps() {
- const stateController = _CoreManager.default.getObjectStateController();
- return stateController.getPendingOps(this._getStateIdentifier());
- }
-
- _clearPendingOps(keysToClear) {
- const pending = this._getPendingOps();
- const latest = pending[pending.length - 1];
- const keys = keysToClear || Object.keys(latest);
- keys.forEach(key => {
- delete latest[key];
- });
- }
- _getDirtyObjectAttributes() {
- const attributes = this.attributes;
- const stateController = _CoreManager.default.getObjectStateController();
- const objectCache = stateController.getObjectCache(this._getStateIdentifier());
- const dirty = {};
- for (const attr in attributes) {
- const val = attributes[attr];
- if (val && typeof val === 'object' && !(val instanceof ParseObject) && !(val instanceof _ParseFile.default) && !(val instanceof _ParseRelation.default)) {
-
-
- try {
- const json = (0, _encode.default)(val, false, true);
- const stringified = JSON.stringify(json);
- if (objectCache[attr] !== stringified) {
- dirty[attr] = val;
- }
- } catch (e) {
-
-
- dirty[attr] = val;
- }
- }
- }
- return dirty;
- }
- _toFullJSON(seen, offline) {
- const json = this.toJSON(seen, offline);
- json.__type = 'Object';
- json.className = this.className;
- return json;
- }
- _getSaveJSON() {
- const pending = this._getPendingOps();
- const dirtyObjects = this._getDirtyObjectAttributes();
- const json = {};
- for (var attr in dirtyObjects) {
- let isDotNotation = false;
- for (let i = 0; i < pending.length; i += 1) {
- for (const field in pending[i]) {
-
- if (field.includes('.')) {
- const fieldName = field.split('.')[0];
- if (fieldName === attr) {
- isDotNotation = true;
- break;
- }
- }
- }
- }
- if (!isDotNotation) {
- json[attr] = new _ParseOp.SetOp(dirtyObjects[attr]).toJSON();
- }
- }
- for (attr in pending[0]) {
- json[attr] = pending[0][attr].toJSON();
- }
- return json;
- }
- _getSaveParams() {
- let method = this.id ? 'PUT' : 'POST';
- const body = this._getSaveJSON();
- let path = 'classes/' + this.className;
- if (_CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID')) {
- if (!this.createdAt) {
- method = 'POST';
- body.objectId = this.id;
- } else {
- method = 'PUT';
- path += '/' + this.id;
- }
- } else if (this.id) {
- path += '/' + this.id;
- } else if (this.className === '_User') {
- path = 'users';
- }
- return {
- method,
- body,
- path
- };
- }
- _finishFetch(serverData) {
- if (!this.id && serverData.objectId) {
- this.id = serverData.objectId;
- }
- const stateController = _CoreManager.default.getObjectStateController();
- stateController.initializeState(this._getStateIdentifier());
- const decoded = {};
- for (const attr in serverData) {
- if (attr === 'ACL') {
- decoded[attr] = new _ParseACL.default(serverData[attr]);
- } else if (attr !== 'objectId') {
- decoded[attr] = (0, _decode.default)(serverData[attr]);
- if (decoded[attr] instanceof _ParseRelation.default) {
- decoded[attr]._ensureParentAndKey(this, attr);
- }
- }
- }
- if (decoded.createdAt && typeof decoded.createdAt === 'string') {
- decoded.createdAt = (0, _parseDate.default)(decoded.createdAt);
- }
- if (decoded.updatedAt && typeof decoded.updatedAt === 'string') {
- decoded.updatedAt = (0, _parseDate.default)(decoded.updatedAt);
- }
- if (!decoded.updatedAt && decoded.createdAt) {
- decoded.updatedAt = decoded.createdAt;
- }
- stateController.commitServerChanges(this._getStateIdentifier(), decoded);
- }
- _setExisted(existed) {
- const stateController = _CoreManager.default.getObjectStateController();
- const state = stateController.getState(this._getStateIdentifier());
- if (state) {
- state.existed = existed;
- }
- }
- _migrateId(serverId) {
- if (this._localId && serverId) {
- if (singleInstance) {
- const stateController = _CoreManager.default.getObjectStateController();
- const oldState = stateController.removeState(this._getStateIdentifier());
- this.id = serverId;
- delete this._localId;
- if (oldState) {
- stateController.initializeState(this._getStateIdentifier(), oldState);
- }
- } else {
- this.id = serverId;
- delete this._localId;
- }
- }
- }
- _handleSaveResponse(response, status) {
- const changes = {};
- const stateController = _CoreManager.default.getObjectStateController();
- const pending = stateController.popPendingState(this._getStateIdentifier());
- for (var attr in pending) {
- if (pending[attr] instanceof _ParseOp.RelationOp) {
- changes[attr] = pending[attr].applyTo(undefined, this, attr);
- } else if (!(attr in response)) {
-
- changes[attr] = pending[attr].applyTo(undefined);
- }
- }
- for (attr in response) {
- if ((attr === 'createdAt' || attr === 'updatedAt') && typeof response[attr] === 'string') {
- changes[attr] = (0, _parseDate.default)(response[attr]);
- } else if (attr === 'ACL') {
- changes[attr] = new _ParseACL.default(response[attr]);
- } else if (attr !== 'objectId') {
- const val = (0, _decode.default)(response[attr]);
- if (val && Object.getPrototypeOf(val) === Object.prototype) {
- changes[attr] = {
- ...this.attributes[attr],
- ...val
- };
- } else {
- changes[attr] = val;
- }
- if (changes[attr] instanceof _ParseOp.UnsetOp) {
- changes[attr] = undefined;
- }
- }
- }
- if (changes.createdAt && !changes.updatedAt) {
- changes.updatedAt = changes.createdAt;
- }
- this._migrateId(response.objectId);
- if (status !== 201) {
- this._setExisted(true);
- }
- stateController.commitServerChanges(this._getStateIdentifier(), changes);
- }
- _handleSaveError() {
- const stateController = _CoreManager.default.getObjectStateController();
- stateController.mergeFirstPendingState(this._getStateIdentifier());
- }
- static _getClassMap() {
- return classMap;
- }
-
- initialize() {
-
- }
-
- toJSON(seen, offline) {
- const seenEntry = this.id ? this.className + ':' + this.id : this;
- seen = seen || [seenEntry];
- const json = {};
- const attrs = this.attributes;
- for (const attr in attrs) {
- if ((attr === 'createdAt' || attr === 'updatedAt') && attrs[attr].toJSON) {
- json[attr] = attrs[attr].toJSON();
- } else {
- json[attr] = (0, _encode.default)(attrs[attr], false, false, seen, offline);
- }
- }
- const pending = this._getPendingOps();
- for (const attr in pending[0]) {
- if (attr.indexOf('.') < 0) {
- json[attr] = pending[0][attr].toJSON(offline);
- }
- }
- if (this.id) {
- json.objectId = this.id;
- }
- return json;
- }
-
- equals(other) {
- if (this === other) {
- return true;
- }
- return other instanceof ParseObject && this.className === other.className && this.id === other.id && typeof this.id !== 'undefined';
- }
-
- dirty(attr) {
- if (!this.id) {
- return true;
- }
- const pendingOps = this._getPendingOps();
- const dirtyObjects = this._getDirtyObjectAttributes();
- if (attr) {
- if (dirtyObjects.hasOwnProperty(attr)) {
- return true;
- }
- for (let i = 0; i < pendingOps.length; i++) {
- if (pendingOps[i].hasOwnProperty(attr)) {
- return true;
- }
- }
- return false;
- }
- if (Object.keys(pendingOps[0]).length !== 0) {
- return true;
- }
- if (Object.keys(dirtyObjects).length !== 0) {
- return true;
- }
- return false;
- }
-
- dirtyKeys() {
- const pendingOps = this._getPendingOps();
- const keys = {};
- for (let i = 0; i < pendingOps.length; i++) {
- for (const attr in pendingOps[i]) {
- keys[attr] = true;
- }
- }
- const dirtyObjects = this._getDirtyObjectAttributes();
- for (const attr in dirtyObjects) {
- keys[attr] = true;
- }
- return Object.keys(keys);
- }
-
- isDataAvailable() {
- const serverData = this._getServerData();
- return !!Object.keys(serverData).length;
- }
-
- toPointer() {
- if (!this.id) {
- throw new Error('Cannot create a pointer to an unsaved ParseObject');
- }
- return {
- __type: 'Pointer',
- className: this.className,
- objectId: this.id
- };
- }
-
- toOfflinePointer() {
- if (!this._localId) {
- throw new Error('Cannot create a offline pointer to a saved ParseObject');
- }
- return {
- __type: 'Object',
- className: this.className,
- _localId: this._localId
- };
- }
-
- get(attr) {
- return this.attributes[attr];
- }
-
- relation(attr) {
- const value = this.get(attr);
- if (value) {
- if (!(value instanceof _ParseRelation.default)) {
- throw new Error('Called relation() on non-relation field ' + attr);
- }
- value._ensureParentAndKey(this, attr);
- return value;
- }
- return new _ParseRelation.default(this, attr);
- }
-
- escape(attr) {
- let val = this.attributes[attr];
- if (val == null) {
- return '';
- }
- if (typeof val !== 'string') {
- if (typeof val.toString !== 'function') {
- return '';
- }
- val = val.toString();
- }
- return (0, _escape.default)(val);
- }
-
- has(attr) {
- const attributes = this.attributes;
- if (attributes.hasOwnProperty(attr)) {
- return attributes[attr] != null;
- }
- return false;
- }
-
- set(key, value, options) {
- let changes = {};
- const newOps = {};
- if (key && typeof key === 'object') {
- changes = key;
- options = value;
- } else if (typeof key === 'string') {
- changes[key] = value;
- } else {
- return this;
- }
- options = options || {};
- let readonly = [];
- if (typeof this.constructor.readOnlyAttributes === 'function') {
- readonly = readonly.concat(this.constructor.readOnlyAttributes());
- }
- for (const k in changes) {
- if (k === 'createdAt' || k === 'updatedAt') {
-
-
- continue;
- }
- if (readonly.indexOf(k) > -1) {
- throw new Error('Cannot modify readonly attribute: ' + k);
- }
- if (options.unset) {
- newOps[k] = new _ParseOp.UnsetOp();
- } else if (changes[k] instanceof _ParseOp.Op) {
- newOps[k] = changes[k];
- } else if (changes[k] && typeof changes[k] === 'object' && typeof changes[k].__op === 'string') {
- newOps[k] = (0, _ParseOp.opFromJSON)(changes[k]);
- } else if (k === 'objectId' || k === 'id') {
- if (typeof changes[k] === 'string') {
- this.id = changes[k];
- }
- } else if (k === 'ACL' && typeof changes[k] === 'object' && !(changes[k] instanceof _ParseACL.default)) {
- newOps[k] = new _ParseOp.SetOp(new _ParseACL.default(changes[k]));
- } else if (changes[k] instanceof _ParseRelation.default) {
- const relation = new _ParseRelation.default(this, k);
- relation.targetClassName = changes[k].targetClassName;
- newOps[k] = new _ParseOp.SetOp(relation);
- } else {
- newOps[k] = new _ParseOp.SetOp(changes[k]);
- }
- }
- const currentAttributes = this.attributes;
-
- const newValues = {};
- for (const attr in newOps) {
- if (newOps[attr] instanceof _ParseOp.RelationOp) {
- newValues[attr] = newOps[attr].applyTo(currentAttributes[attr], this, attr);
- } else if (!(newOps[attr] instanceof _ParseOp.UnsetOp)) {
- newValues[attr] = newOps[attr].applyTo(currentAttributes[attr]);
- }
- }
-
- if (!options.ignoreValidation) {
- const validation = this.validate(newValues);
- if (validation) {
- if (typeof options.error === 'function') {
- options.error(this, validation);
- }
- return false;
- }
- }
-
- const pendingOps = this._getPendingOps();
- const last = pendingOps.length - 1;
- const stateController = _CoreManager.default.getObjectStateController();
- for (const attr in newOps) {
- const nextOp = newOps[attr].mergeWith(pendingOps[last][attr]);
- stateController.setPendingOp(this._getStateIdentifier(), attr, nextOp);
- }
- return this;
- }
-
- unset(attr, options) {
- options = options || {};
- options.unset = true;
- return this.set(attr, null, options);
- }
-
- increment(attr, amount) {
- if (typeof amount === 'undefined') {
- amount = 1;
- }
- if (typeof amount !== 'number') {
- throw new Error('Cannot increment by a non-numeric amount.');
- }
- return this.set(attr, new _ParseOp.IncrementOp(amount));
- }
-
- decrement(attr, amount) {
- if (typeof amount === 'undefined') {
- amount = 1;
- }
- if (typeof amount !== 'number') {
- throw new Error('Cannot decrement by a non-numeric amount.');
- }
- return this.set(attr, new _ParseOp.IncrementOp(amount * -1));
- }
-
- add(attr, item) {
- return this.set(attr, new _ParseOp.AddOp([item]));
- }
-
- addAll(attr, items) {
- return this.set(attr, new _ParseOp.AddOp(items));
- }
-
- addUnique(attr, item) {
- return this.set(attr, new _ParseOp.AddUniqueOp([item]));
- }
-
- addAllUnique(attr, items) {
- return this.set(attr, new _ParseOp.AddUniqueOp(items));
- }
-
- remove(attr, item) {
- return this.set(attr, new _ParseOp.RemoveOp([item]));
- }
-
- removeAll(attr, items) {
- return this.set(attr, new _ParseOp.RemoveOp(items));
- }
-
- op(attr) {
- const pending = this._getPendingOps();
- for (let i = pending.length; i--;) {
- if (pending[i][attr]) {
- return pending[i][attr];
- }
- }
- }
-
- clone() {
- const clone = new this.constructor(this.className);
- let attributes = this.attributes;
- if (typeof this.constructor.readOnlyAttributes === 'function') {
- const readonly = this.constructor.readOnlyAttributes() || [];
-
-
- const copy = {};
- for (const a in attributes) {
- if (readonly.indexOf(a) < 0) {
- copy[a] = attributes[a];
- }
- }
- attributes = copy;
- }
- if (clone.set) {
- clone.set(attributes);
- }
- return clone;
- }
-
- newInstance() {
- const clone = new this.constructor(this.className);
- clone.id = this.id;
- if (singleInstance) {
-
- return clone;
- }
- const stateController = _CoreManager.default.getObjectStateController();
- if (stateController) {
- stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier());
- }
- return clone;
- }
-
- isNew() {
- return !this.id;
- }
-
- existed() {
- if (!this.id) {
- return false;
- }
- const stateController = _CoreManager.default.getObjectStateController();
- const state = stateController.getState(this._getStateIdentifier());
- if (state) {
- return state.existed;
- }
- return false;
- }
-
- async exists(options) {
- if (!this.id) {
- return false;
- }
- try {
- const ParseQuery = _CoreManager.default.getParseQuery();
- const query = new ParseQuery(this.className);
- await query.get(this.id, options);
- return true;
- } catch (e) {
- if (e.code === _ParseError.default.OBJECT_NOT_FOUND) {
- return false;
- }
- throw e;
- }
- }
-
- isValid() {
- return !this.validate(this.attributes);
- }
-
- validate(attrs) {
- if (attrs.hasOwnProperty('ACL') && !(attrs.ACL instanceof _ParseACL.default)) {
- return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'ACL must be a Parse ACL.');
- }
- for (const key in attrs) {
- if (!/^[A-Za-z][0-9A-Za-z_.]*$/.test(key)) {
- return new _ParseError.default(_ParseError.default.INVALID_KEY_NAME);
- }
- }
- return false;
- }
-
- getACL() {
- const acl = this.get('ACL');
- if (acl instanceof _ParseACL.default) {
- return acl;
- }
- return null;
- }
-
- setACL(acl, options) {
- return this.set('ACL', acl, options);
- }
-
- revert(...keys) {
- let keysToRevert;
- if (keys.length) {
- keysToRevert = [];
- for (const key of keys) {
- if (typeof key === 'string') {
- keysToRevert.push(key);
- } else {
- throw new Error('Parse.Object#revert expects either no, or a list of string, arguments.');
- }
- }
- }
- this._clearPendingOps(keysToRevert);
- }
-
- clear() {
- const attributes = this.attributes;
- const erasable = {};
- let readonly = ['createdAt', 'updatedAt'];
- if (typeof this.constructor.readOnlyAttributes === 'function') {
- readonly = readonly.concat(this.constructor.readOnlyAttributes());
- }
- for (const attr in attributes) {
- if (readonly.indexOf(attr) < 0) {
- erasable[attr] = true;
- }
- }
- return this.set(erasable, {
- unset: true
- });
- }
-
- fetch(options) {
- options = options || {};
- const fetchOptions = {};
- if (options.hasOwnProperty('useMasterKey')) {
- fetchOptions.useMasterKey = options.useMasterKey;
- }
- if (options.hasOwnProperty('sessionToken')) {
- fetchOptions.sessionToken = options.sessionToken;
- }
- if (options.hasOwnProperty('context') && typeof options.context === 'object') {
- fetchOptions.context = options.context;
- }
- if (options.hasOwnProperty('include')) {
- fetchOptions.include = [];
- if (Array.isArray(options.include)) {
- options.include.forEach(key => {
- if (Array.isArray(key)) {
- fetchOptions.include = fetchOptions.include.concat(key);
- } else {
- fetchOptions.include.push(key);
- }
- });
- } else {
- fetchOptions.include.push(options.include);
- }
- }
- const controller = _CoreManager.default.getObjectController();
- return controller.fetch(this, true, fetchOptions);
- }
-
- fetchWithInclude(keys, options) {
- options = options || {};
- options.include = keys;
- return this.fetch(options);
- }
-
- async saveEventually(options) {
- try {
- await this.save(null, options);
- } catch (e) {
- if (e.code === _ParseError.default.CONNECTION_FAILED) {
- await _CoreManager.default.getEventuallyQueue().save(this, options);
- _CoreManager.default.getEventuallyQueue().poll();
- }
- }
- return this;
- }
-
- save(arg1, arg2, arg3) {
- let attrs;
- let options;
- if (typeof arg1 === 'object' || typeof arg1 === 'undefined') {
- attrs = arg1;
- if (typeof arg2 === 'object') {
- options = arg2;
- }
- } else {
- attrs = {};
- attrs[arg1] = arg2;
- options = arg3;
- }
- options = options || {};
- if (attrs) {
- let validationError;
- options.error = (_, validation) => {
- validationError = validation;
- };
- const success = this.set(attrs, options);
- if (!success) {
- return Promise.reject(validationError);
- }
- }
- const saveOptions = {};
- if (options.hasOwnProperty('useMasterKey')) {
- saveOptions.useMasterKey = !!options.useMasterKey;
- }
- if (options.hasOwnProperty('sessionToken') && typeof options.sessionToken === 'string') {
- saveOptions.sessionToken = options.sessionToken;
- }
- if (options.hasOwnProperty('installationId') && typeof options.installationId === 'string') {
- saveOptions.installationId = options.installationId;
- }
- if (options.hasOwnProperty('context') && typeof options.context === 'object') {
- saveOptions.context = options.context;
- }
- const controller = _CoreManager.default.getObjectController();
- const unsaved = options.cascadeSave !== false ? (0, _unsavedChildren.default)(this) : null;
- return controller.save(unsaved, saveOptions).then(() => {
- return controller.save(this, saveOptions);
- });
- }
-
- async destroyEventually(options) {
- try {
- await this.destroy(options);
- } catch (e) {
- if (e.code === _ParseError.default.CONNECTION_FAILED) {
- await _CoreManager.default.getEventuallyQueue().destroy(this, options);
- _CoreManager.default.getEventuallyQueue().poll();
- }
- }
- return this;
- }
-
- destroy(options) {
- options = options || {};
- const destroyOptions = {};
- if (options.hasOwnProperty('useMasterKey')) {
- destroyOptions.useMasterKey = options.useMasterKey;
- }
- if (options.hasOwnProperty('sessionToken')) {
- destroyOptions.sessionToken = options.sessionToken;
- }
- if (options.hasOwnProperty('context') && typeof options.context === 'object') {
- destroyOptions.context = options.context;
- }
- if (!this.id) {
- return Promise.resolve();
- }
- return _CoreManager.default.getObjectController().destroy(this, destroyOptions);
- }
-
- pin() {
- return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
- }
-
- unPin() {
- return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
- }
-
- async isPinned() {
- const localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- const objectKey = localDatastore.getKeyForObject(this);
- const pin = await localDatastore.fromPinWithName(objectKey);
- return pin.length > 0;
- }
-
- pinWithName(name) {
- return ParseObject.pinAllWithName(name, [this]);
- }
-
- unPinWithName(name) {
- return ParseObject.unPinAllWithName(name, [this]);
- }
-
- async fetchFromLocalDatastore() {
- const localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- throw new Error('Parse.enableLocalDatastore() must be called first');
- }
- const objectKey = localDatastore.getKeyForObject(this);
- const pinned = await localDatastore._serializeObject(objectKey);
- if (!pinned) {
- throw new Error('Cannot fetch an unsaved ParseObject');
- }
- const result = ParseObject.fromJSON(pinned);
- this._finishFetch(result.toJSON());
- return this;
- }
-
- static _clearAllState() {
- const stateController = _CoreManager.default.getObjectStateController();
- stateController.clearAllState();
- }
-
- static fetchAll(list, options = {}) {
- const queryOptions = {};
- if (options.hasOwnProperty('useMasterKey')) {
- queryOptions.useMasterKey = options.useMasterKey;
- }
- if (options.hasOwnProperty('sessionToken')) {
- queryOptions.sessionToken = options.sessionToken;
- }
- if (options.hasOwnProperty('include')) {
- queryOptions.include = ParseObject.handleIncludeOptions(options);
- }
- return _CoreManager.default.getObjectController().fetch(list, true, queryOptions);
- }
-
- static fetchAllWithInclude(list, keys, options) {
- options = options || {};
- options.include = keys;
- return ParseObject.fetchAll(list, options);
- }
-
- static fetchAllIfNeededWithInclude(list, keys, options) {
- options = options || {};
- options.include = keys;
- return ParseObject.fetchAllIfNeeded(list, options);
- }
-
- static fetchAllIfNeeded(list, options) {
- options = options || {};
- const queryOptions = {};
- if (options.hasOwnProperty('useMasterKey')) {
- queryOptions.useMasterKey = options.useMasterKey;
- }
- if (options.hasOwnProperty('sessionToken')) {
- queryOptions.sessionToken = options.sessionToken;
- }
- if (options.hasOwnProperty('include')) {
- queryOptions.include = ParseObject.handleIncludeOptions(options);
- }
- return _CoreManager.default.getObjectController().fetch(list, false, queryOptions);
- }
- static handleIncludeOptions(options) {
- let include = [];
- if (Array.isArray(options.include)) {
- options.include.forEach(key => {
- if (Array.isArray(key)) {
- include = include.concat(key);
- } else {
- include.push(key);
- }
- });
- } else {
- include.push(options.include);
- }
- return include;
- }
-
- static destroyAll(list, options = {}) {
- const destroyOptions = {};
- if (options.hasOwnProperty('useMasterKey')) {
- destroyOptions.useMasterKey = options.useMasterKey;
- }
- if (options.hasOwnProperty('sessionToken')) {
- destroyOptions.sessionToken = options.sessionToken;
- }
- if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
- destroyOptions.batchSize = options.batchSize;
- }
- if (options.hasOwnProperty('context') && typeof options.context === 'object') {
- destroyOptions.context = options.context;
- }
- return _CoreManager.default.getObjectController().destroy(list, destroyOptions);
- }
-
- static saveAll(list, options = {}) {
- const saveOptions = {};
- if (options.hasOwnProperty('useMasterKey')) {
- saveOptions.useMasterKey = options.useMasterKey;
- }
- if (options.hasOwnProperty('sessionToken')) {
- saveOptions.sessionToken = options.sessionToken;
- }
- if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
- saveOptions.batchSize = options.batchSize;
- }
- if (options.hasOwnProperty('context') && typeof options.context === 'object') {
- saveOptions.context = options.context;
- }
- return _CoreManager.default.getObjectController().save(list, saveOptions);
- }
-
- static createWithoutData(id) {
- const obj = new this();
- obj.id = id;
- return obj;
- }
-
- static fromJSON(json, override, dirty) {
- if (!json.className) {
- throw new Error('Cannot create an object without a className');
- }
- const constructor = classMap[json.className];
- const o = constructor ? new constructor(json.className) : new ParseObject(json.className);
- const otherAttributes = {};
- for (const attr in json) {
- if (attr !== 'className' && attr !== '__type') {
- otherAttributes[attr] = json[attr];
- if (dirty) {
- o.set(attr, json[attr]);
- }
- }
- }
- if (override) {
-
- if (otherAttributes.objectId) {
- o.id = otherAttributes.objectId;
- }
- let preserved = null;
- if (typeof o._preserveFieldsOnFetch === 'function') {
- preserved = o._preserveFieldsOnFetch();
- }
- o._clearServerData();
- if (preserved) {
- o._finishFetch(preserved);
- }
- }
- o._finishFetch(otherAttributes);
- if (json.objectId) {
- o._setExisted(true);
- }
- return o;
- }
-
- static registerSubclass(className, constructor) {
- if (typeof className !== 'string') {
- throw new TypeError('The first argument must be a valid class name.');
- }
- if (typeof constructor === 'undefined') {
- throw new TypeError('You must supply a subclass constructor.');
- }
- if (typeof constructor !== 'function') {
- throw new TypeError('You must register the subclass constructor. ' + 'Did you attempt to register an instance of the subclass?');
- }
- classMap[className] = constructor;
- if (!constructor.className) {
- constructor.className = className;
- }
- }
- /**
- * Unegisters a subclass of Parse.Object with a specific class name.
- *
- * @param {string} className The class name of the subclass
- */
- static unregisterSubclass(className) {
- if (typeof className !== 'string') {
- throw new TypeError('The first argument must be a valid class name.');
- }
- delete classMap[className];
- }
-
- static extend(className, protoProps, classProps) {
- if (typeof className !== 'string') {
- if (className && typeof className.className === 'string') {
- return ParseObject.extend(className.className, className, protoProps);
- } else {
- throw new Error("Parse.Object.extend's first argument should be the className.");
- }
- }
- let adjustedClassName = className;
- if (adjustedClassName === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
- adjustedClassName = '_User';
- }
- let parentProto = ParseObject.prototype;
- if (this.hasOwnProperty('__super__') && this.__super__) {
- parentProto = this.prototype;
- }
- let ParseObjectSubclass = function (attributes, options) {
- this.className = adjustedClassName;
- this._objCount = objectCount++;
-
- if (typeof this.initialize === 'function') {
- this.initialize.apply(this, arguments);
- }
- if (this._initializers) {
- for (const initializer of this._initializers) {
- initializer.apply(this, arguments);
- }
- }
- if (attributes && typeof attributes === 'object') {
- if (!this.set(attributes || {}, options)) {
- throw new Error("Can't create an invalid Parse Object");
- }
- }
- };
- if (classMap[adjustedClassName]) {
- ParseObjectSubclass = classMap[adjustedClassName];
- } else {
- ParseObjectSubclass.extend = function (name, protoProps, classProps) {
- if (typeof name === 'string') {
- return ParseObject.extend.call(ParseObjectSubclass, name, protoProps, classProps);
- }
- return ParseObject.extend.call(ParseObjectSubclass, adjustedClassName, name, protoProps);
- };
- ParseObjectSubclass.createWithoutData = ParseObject.createWithoutData;
- ParseObjectSubclass.className = adjustedClassName;
- ParseObjectSubclass.__super__ = parentProto;
- ParseObjectSubclass.prototype = Object.create(parentProto, {
- constructor: {
- value: ParseObjectSubclass,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- }
- if (protoProps) {
- for (const prop in protoProps) {
- if (prop === 'initialize') {
- Object.defineProperty(ParseObjectSubclass.prototype, '_initializers', {
- value: [...(ParseObjectSubclass.prototype._initializers || []), protoProps[prop]],
- enumerable: false,
- writable: true,
- configurable: true
- });
- continue;
- }
- if (prop !== 'className') {
- Object.defineProperty(ParseObjectSubclass.prototype, prop, {
- value: protoProps[prop],
- enumerable: false,
- writable: true,
- configurable: true
- });
- }
- }
- }
- if (classProps) {
- for (const prop in classProps) {
- if (prop !== 'className') {
- Object.defineProperty(ParseObjectSubclass, prop, {
- value: classProps[prop],
- enumerable: false,
- writable: true,
- configurable: true
- });
- }
- }
- }
- classMap[adjustedClassName] = ParseObjectSubclass;
- return ParseObjectSubclass;
- }
-
- static enableSingleInstance() {
- singleInstance = true;
- _CoreManager.default.setObjectStateController(SingleInstanceStateController);
- }
-
- static disableSingleInstance() {
- singleInstance = false;
- _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
- }
-
- static pinAll(objects) {
- const localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
- }
-
- static pinAllWithName(name, objects) {
- const localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return localDatastore._handlePinAllWithName(name, objects);
- }
-
- static unPinAll(objects) {
- const localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
- }
-
- static unPinAllWithName(name, objects) {
- const localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return localDatastore._handleUnPinAllWithName(name, objects);
- }
-
- static unPinAllObjects() {
- const localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return localDatastore.unPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
- }
-
- static unPinAllObjectsWithName(name) {
- const localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return localDatastore.unPinWithName(_LocalDatastoreUtils.PIN_PREFIX + name);
- }
- }
- const DefaultController = {
- fetch(target, forceFetch, options) {
- const localDatastore = _CoreManager.default.getLocalDatastore();
- if (Array.isArray(target)) {
- if (target.length < 1) {
- return Promise.resolve([]);
- }
- const objs = [];
- const ids = [];
- let className = null;
- const results = [];
- let error = null;
- target.forEach(el => {
- if (error) {
- return;
- }
- if (!className) {
- className = el.className;
- }
- if (className !== el.className) {
- error = new _ParseError.default(_ParseError.default.INVALID_CLASS_NAME, 'All objects should be of the same class');
- }
- if (!el.id) {
- error = new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'All objects must have an ID');
- }
- if (forceFetch || !el.isDataAvailable()) {
- ids.push(el.id);
- objs.push(el);
- }
- results.push(el);
- });
- if (error) {
- return Promise.reject(error);
- }
- const ParseQuery = _CoreManager.default.getParseQuery();
- const query = new ParseQuery(className);
- query.containedIn('objectId', ids);
- if (options && options.include) {
- query.include(options.include);
- }
- query._limit = ids.length;
- return query.find(options).then(async objects => {
- const idMap = {};
- objects.forEach(o => {
- idMap[o.id] = o;
- });
- for (let i = 0; i < objs.length; i++) {
- const obj = objs[i];
- if (!obj || !obj.id || !idMap[obj.id]) {
- if (forceFetch) {
- return Promise.reject(new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'All objects must exist on the server.'));
- }
- }
- }
- if (!singleInstance) {
-
- for (let i = 0; i < results.length; i++) {
- const obj = results[i];
- if (obj && obj.id && idMap[obj.id]) {
- const id = obj.id;
- obj._finishFetch(idMap[id].toJSON());
- results[i] = idMap[id];
- }
- }
- }
- for (const object of results) {
- await localDatastore._updateObjectIfPinned(object);
- }
- return Promise.resolve(results);
- });
- } else if (target instanceof ParseObject) {
- if (!target.id) {
- return Promise.reject(new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'Object does not have an ID'));
- }
- const RESTController = _CoreManager.default.getRESTController();
- const params = {};
- if (options && options.include) {
- params.include = options.include.join();
- }
- return RESTController.request('GET', 'classes/' + target.className + '/' + target._getId(), params, options).then(async response => {
- target._clearPendingOps();
- target._clearServerData();
- target._finishFetch(response);
- await localDatastore._updateObjectIfPinned(target);
- return target;
- });
- }
- return Promise.resolve(undefined);
- },
- async destroy(target, options) {
- const batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
- const localDatastore = _CoreManager.default.getLocalDatastore();
- const RESTController = _CoreManager.default.getRESTController();
- if (Array.isArray(target)) {
- if (target.length < 1) {
- return Promise.resolve([]);
- }
- const batches = [[]];
- target.forEach(obj => {
- if (!obj.id) {
- return;
- }
- batches[batches.length - 1].push(obj);
- if (batches[batches.length - 1].length >= batchSize) {
- batches.push([]);
- }
- });
- if (batches[batches.length - 1].length === 0) {
-
- batches.pop();
- }
- let deleteCompleted = Promise.resolve();
- const errors = [];
- batches.forEach(batch => {
- deleteCompleted = deleteCompleted.then(() => {
- return RESTController.request('POST', 'batch', {
- requests: batch.map(obj => {
- return {
- method: 'DELETE',
- path: getServerUrlPath() + 'classes/' + obj.className + '/' + obj._getId(),
- body: {}
- };
- })
- }, options).then(results => {
- for (let i = 0; i < results.length; i++) {
- if (results[i] && results[i].hasOwnProperty('error')) {
- const err = new _ParseError.default(results[i].error.code, results[i].error.error);
- err.object = batch[i];
- errors.push(err);
- }
- }
- });
- });
- });
- return deleteCompleted.then(async () => {
- if (errors.length) {
- const aggregate = new _ParseError.default(_ParseError.default.AGGREGATE_ERROR);
- aggregate.errors = errors;
- return Promise.reject(aggregate);
- }
- for (const object of target) {
- await localDatastore._destroyObjectIfPinned(object);
- }
- return Promise.resolve(target);
- });
- } else if (target instanceof ParseObject) {
- return RESTController.request('DELETE', 'classes/' + target.className + '/' + target._getId(), {}, options).then(async () => {
- await localDatastore._destroyObjectIfPinned(target);
- return Promise.resolve(target);
- });
- }
- return Promise.resolve(target);
- },
- save(target, options) {
- const batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
- const localDatastore = _CoreManager.default.getLocalDatastore();
- const mapIdForPin = {};
- const RESTController = _CoreManager.default.getRESTController();
- const stateController = _CoreManager.default.getObjectStateController();
- const allowCustomObjectId = _CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID');
- options = options || {};
- options.returnStatus = options.returnStatus || true;
- if (Array.isArray(target)) {
- if (target.length < 1) {
- return Promise.resolve([]);
- }
- let unsaved = target.concat();
- for (let i = 0; i < target.length; i++) {
- const target_i = target[i];
- if (target_i instanceof ParseObject) {
- unsaved = unsaved.concat((0, _unsavedChildren.default)(target_i, true));
- }
- }
- unsaved = (0, _unique.default)(unsaved);
- const filesSaved = [];
- let pending = [];
- unsaved.forEach(el => {
- if (el instanceof _ParseFile.default) {
- filesSaved.push(el.save(options));
- } else if (el instanceof ParseObject) {
- pending.push(el);
- }
- });
- return Promise.all(filesSaved).then(() => {
- let objectError = null;
- return (0, _promiseUtils.continueWhile)(() => {
- return pending.length > 0;
- }, () => {
- const batch = [];
- const nextPending = [];
- pending.forEach(el => {
- if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(el, 'id') && !el.id) {
- throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null');
- }
- if (batch.length < batchSize && (0, _canBeSerialized.default)(el)) {
- batch.push(el);
- } else {
- nextPending.push(el);
- }
- });
- pending = nextPending;
- if (batch.length < 1) {
- return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Tried to save a batch with a cycle.'));
- }
-
-
- const batchReturned = (0, _promiseUtils.resolvingPromise)();
- const batchReady = [];
- const batchTasks = [];
- batch.forEach((obj, index) => {
- const ready = (0, _promiseUtils.resolvingPromise)();
- batchReady.push(ready);
- stateController.pushPendingState(obj._getStateIdentifier());
- batchTasks.push(stateController.enqueueTask(obj._getStateIdentifier(), function () {
- ready.resolve();
- return batchReturned.then(responses => {
- if (responses[index].hasOwnProperty('success')) {
- const objectId = responses[index].success.objectId;
- const status = responses[index]._status;
- delete responses[index]._status;
- delete responses[index]._headers;
- delete responses[index]._xhr;
- mapIdForPin[objectId] = obj._localId;
- obj._handleSaveResponse(responses[index].success, status);
- } else {
- if (!objectError && responses[index].hasOwnProperty('error')) {
- const serverError = responses[index].error;
- objectError = new _ParseError.default(serverError.code, serverError.error);
-
- pending = [];
- }
- obj._handleSaveError();
- }
- });
- }));
- });
- (0, _promiseUtils.when)(batchReady).then(() => {
-
- return RESTController.request('POST', 'batch', {
- requests: batch.map(obj => {
- const params = obj._getSaveParams();
- params.path = getServerUrlPath() + params.path;
- return params;
- })
- }, options);
- }).then(batchReturned.resolve, error => {
- batchReturned.reject(new _ParseError.default(_ParseError.default.INCORRECT_TYPE, error.message));
- });
- return (0, _promiseUtils.when)(batchTasks);
- }).then(async () => {
- if (objectError) {
- return Promise.reject(objectError);
- }
- for (const object of target) {
-
- if (object instanceof ParseObject) {
- await localDatastore._updateLocalIdForObject(mapIdForPin[object.id], object);
- await localDatastore._updateObjectIfPinned(object);
- }
- }
- return Promise.resolve(target);
- });
- });
- } else if (target instanceof ParseObject) {
- if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(target, 'id') && !target.id) {
- throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null');
- }
-
- target._getId();
- const localId = target._localId;
-
- const targetCopy = target;
- const task = function () {
- const params = targetCopy._getSaveParams();
- return RESTController.request(params.method, params.path, params.body, options).then(response => {
- const status = response._status;
- delete response._status;
- delete response._headers;
- delete response._xhr;
- targetCopy._handleSaveResponse(response, status);
- }, error => {
- targetCopy._handleSaveError();
- return Promise.reject(error);
- });
- };
- stateController.pushPendingState(target._getStateIdentifier());
- return stateController.enqueueTask(target._getStateIdentifier(), task).then(async () => {
- await localDatastore._updateLocalIdForObject(localId, target);
- await localDatastore._updateObjectIfPinned(target);
- return target;
- }, error => {
- return Promise.reject(error);
- });
- }
- return Promise.resolve(undefined);
- }
- };
- _CoreManager.default.setParseObject(ParseObject);
- _CoreManager.default.setObjectController(DefaultController);
- var _default = exports.default = ParseObject;
|