12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646 |
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- exports.default = void 0;
- var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
- var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
- var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
- var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
- var _CoreManager = _interopRequireDefault(require("./CoreManager"));
- var _canBeSerialized = _interopRequireDefault(require("./canBeSerialized"));
- var _decode = _interopRequireDefault(require("./decode"));
- var _encode = _interopRequireDefault(require("./encode"));
- var _escape2 = _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;
- }
- var classMap = {};
- var objectCount = 0;
- var singleInstance = !_CoreManager.default.get('IS_NODE');
- if (singleInstance) {
- _CoreManager.default.setObjectStateController(SingleInstanceStateController);
- } else {
- _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
- }
- function getServerUrlPath() {
- var serverUrl = _CoreManager.default.get('SERVER_URL');
- if (serverUrl[serverUrl.length - 1] !== '/') {
- serverUrl += '/';
- }
- var url = serverUrl.replace(/https?:\/\//, '');
- return url.substr(url.indexOf('/'));
- }
- var ParseObject = function () {
- function ParseObject(className, attributes, options) {
- (0, _classCallCheck2.default)(this, ParseObject);
- if (typeof this.initialize === 'function') {
- this.initialize.apply(this, arguments);
- }
- var 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 (var 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");
- }
- }
- return (0, _createClass2.default)(ParseObject, [{
- key: "attributes",
- get: function () {
- var stateController = _CoreManager.default.getObjectStateController();
- return Object.freeze(stateController.estimateAttributes(this._getStateIdentifier()));
- }
- }, {
- key: "createdAt",
- get: function () {
- return this._getServerData().createdAt;
- }
- }, {
- key: "updatedAt",
- get: function () {
- return this._getServerData().updatedAt;
- }
- }, {
- key: "_getId",
- value: function () {
- if (typeof this.id === 'string') {
- return this.id;
- }
- if (typeof this._localId === 'string') {
- return this._localId;
- }
- var localId = 'local' + (0, _uuid.default)();
- this._localId = localId;
- return localId;
- }
- }, {
- key: "_getStateIdentifier",
- value: function () {
- if (singleInstance) {
- var id = this.id;
- if (!id) {
- id = this._getId();
- }
- return {
- id: id,
- className: this.className
- };
- } else {
- return this;
- }
- }
- }, {
- key: "_getServerData",
- value: function () {
- var stateController = _CoreManager.default.getObjectStateController();
- return stateController.getServerData(this._getStateIdentifier());
- }
- }, {
- key: "_clearServerData",
- value: function () {
- var serverData = this._getServerData();
- var unset = {};
- for (var attr in serverData) {
- unset[attr] = undefined;
- }
- var stateController = _CoreManager.default.getObjectStateController();
- stateController.setServerData(this._getStateIdentifier(), unset);
- }
- }, {
- key: "_getPendingOps",
- value: function () {
- var stateController = _CoreManager.default.getObjectStateController();
- return stateController.getPendingOps(this._getStateIdentifier());
- }
- }, {
- key: "_clearPendingOps",
- value: function (keysToClear) {
- var pending = this._getPendingOps();
- var latest = pending[pending.length - 1];
- var keys = keysToClear || Object.keys(latest);
- keys.forEach(function (key) {
- delete latest[key];
- });
- }
- }, {
- key: "_getDirtyObjectAttributes",
- value: function () {
- var attributes = this.attributes;
- var stateController = _CoreManager.default.getObjectStateController();
- var objectCache = stateController.getObjectCache(this._getStateIdentifier());
- var dirty = {};
- for (var attr in attributes) {
- var val = attributes[attr];
- if (val && typeof val === 'object' && !(val instanceof ParseObject) && !(val instanceof _ParseFile.default) && !(val instanceof _ParseRelation.default)) {
- try {
- var json = (0, _encode.default)(val, false, true);
- var stringified = JSON.stringify(json);
- if (objectCache[attr] !== stringified) {
- dirty[attr] = val;
- }
- } catch (e) {
- dirty[attr] = val;
- }
- }
- }
- return dirty;
- }
- }, {
- key: "_toFullJSON",
- value: function (seen, offline) {
- var json = this.toJSON(seen, offline);
- json.__type = 'Object';
- json.className = this.className;
- return json;
- }
- }, {
- key: "_getSaveJSON",
- value: function () {
- var pending = this._getPendingOps();
- var dirtyObjects = this._getDirtyObjectAttributes();
- var json = {};
- for (var attr in dirtyObjects) {
- var isDotNotation = false;
- for (var i = 0; i < pending.length; i += 1) {
- for (var field in pending[i]) {
- if (field.includes('.')) {
- var 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;
- }
- }, {
- key: "_getSaveParams",
- value: function () {
- var method = this.id ? 'PUT' : 'POST';
- var body = this._getSaveJSON();
- var 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: method,
- body: body,
- path: path
- };
- }
- }, {
- key: "_finishFetch",
- value: function (serverData) {
- if (!this.id && serverData.objectId) {
- this.id = serverData.objectId;
- }
- var stateController = _CoreManager.default.getObjectStateController();
- stateController.initializeState(this._getStateIdentifier());
- var decoded = {};
- for (var 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);
- }
- }, {
- key: "_setExisted",
- value: function (existed) {
- var stateController = _CoreManager.default.getObjectStateController();
- var state = stateController.getState(this._getStateIdentifier());
- if (state) {
- state.existed = existed;
- }
- }
- }, {
- key: "_migrateId",
- value: function (serverId) {
- if (this._localId && serverId) {
- if (singleInstance) {
- var stateController = _CoreManager.default.getObjectStateController();
- var 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;
- }
- }
- }
- }, {
- key: "_handleSaveResponse",
- value: function (response, status) {
- var changes = {};
- var stateController = _CoreManager.default.getObjectStateController();
- var 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') {
- var val = (0, _decode.default)(response[attr]);
- if (val && Object.getPrototypeOf(val) === Object.prototype) {
- changes[attr] = Object.assign({}, 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);
- }
- }, {
- key: "_handleSaveError",
- value: function () {
- var stateController = _CoreManager.default.getObjectStateController();
- stateController.mergeFirstPendingState(this._getStateIdentifier());
- }
- }, {
- key: "initialize",
- value: function () {}
- }, {
- key: "toJSON",
- value: function (seen, offline) {
- var seenEntry = this.id ? this.className + ':' + this.id : this;
- seen = seen || [seenEntry];
- var json = {};
- var attrs = this.attributes;
- for (var 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);
- }
- }
- var pending = this._getPendingOps();
- for (var _attr in pending[0]) {
- if (_attr.indexOf('.') < 0) {
- json[_attr] = pending[0][_attr].toJSON(offline);
- }
- }
- if (this.id) {
- json.objectId = this.id;
- }
- return json;
- }
- }, {
- key: "equals",
- value: function (other) {
- if (this === other) {
- return true;
- }
- return other instanceof ParseObject && this.className === other.className && this.id === other.id && typeof this.id !== 'undefined';
- }
- }, {
- key: "dirty",
- value: function (attr) {
- if (!this.id) {
- return true;
- }
- var pendingOps = this._getPendingOps();
- var dirtyObjects = this._getDirtyObjectAttributes();
- if (attr) {
- if (dirtyObjects.hasOwnProperty(attr)) {
- return true;
- }
- for (var 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;
- }
- }, {
- key: "dirtyKeys",
- value: function () {
- var pendingOps = this._getPendingOps();
- var keys = {};
- for (var i = 0; i < pendingOps.length; i++) {
- for (var attr in pendingOps[i]) {
- keys[attr] = true;
- }
- }
- var dirtyObjects = this._getDirtyObjectAttributes();
- for (var _attr2 in dirtyObjects) {
- keys[_attr2] = true;
- }
- return Object.keys(keys);
- }
- }, {
- key: "isDataAvailable",
- value: function () {
- var serverData = this._getServerData();
- return !!Object.keys(serverData).length;
- }
- }, {
- key: "toPointer",
- value: function () {
- if (!this.id) {
- throw new Error('Cannot create a pointer to an unsaved ParseObject');
- }
- return {
- __type: 'Pointer',
- className: this.className,
- objectId: this.id
- };
- }
- }, {
- key: "toOfflinePointer",
- value: function () {
- if (!this._localId) {
- throw new Error('Cannot create a offline pointer to a saved ParseObject');
- }
- return {
- __type: 'Object',
- className: this.className,
- _localId: this._localId
- };
- }
- }, {
- key: "get",
- value: function (attr) {
- return this.attributes[attr];
- }
- }, {
- key: "relation",
- value: function (attr) {
- var 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);
- }
- }, {
- key: "escape",
- value: function (attr) {
- var val = this.attributes[attr];
- if (val == null) {
- return '';
- }
- if (typeof val !== 'string') {
- if (typeof val.toString !== 'function') {
- return '';
- }
- val = val.toString();
- }
- return (0, _escape2.default)(val);
- }
- }, {
- key: "has",
- value: function (attr) {
- var attributes = this.attributes;
- if (attributes.hasOwnProperty(attr)) {
- return attributes[attr] != null;
- }
- return false;
- }
- }, {
- key: "set",
- value: function (key, value, options) {
- var changes = {};
- var newOps = {};
- if (key && typeof key === 'object') {
- changes = key;
- options = value;
- } else if (typeof key === 'string') {
- changes[key] = value;
- } else {
- return this;
- }
- options = options || {};
- var readonly = [];
- if (typeof this.constructor.readOnlyAttributes === 'function') {
- readonly = readonly.concat(this.constructor.readOnlyAttributes());
- }
- for (var 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) {
- var 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]);
- }
- }
- var currentAttributes = this.attributes;
- var newValues = {};
- for (var 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) {
- var validation = this.validate(newValues);
- if (validation) {
- if (typeof options.error === 'function') {
- options.error(this, validation);
- }
- return false;
- }
- }
- var pendingOps = this._getPendingOps();
- var last = pendingOps.length - 1;
- var stateController = _CoreManager.default.getObjectStateController();
- for (var _attr3 in newOps) {
- var nextOp = newOps[_attr3].mergeWith(pendingOps[last][_attr3]);
- stateController.setPendingOp(this._getStateIdentifier(), _attr3, nextOp);
- }
- return this;
- }
- }, {
- key: "unset",
- value: function (attr, options) {
- options = options || {};
- options.unset = true;
- return this.set(attr, null, options);
- }
- }, {
- key: "increment",
- value: function (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));
- }
- }, {
- key: "decrement",
- value: function (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));
- }
- }, {
- key: "add",
- value: function (attr, item) {
- return this.set(attr, new _ParseOp.AddOp([item]));
- }
- }, {
- key: "addAll",
- value: function (attr, items) {
- return this.set(attr, new _ParseOp.AddOp(items));
- }
- }, {
- key: "addUnique",
- value: function (attr, item) {
- return this.set(attr, new _ParseOp.AddUniqueOp([item]));
- }
- }, {
- key: "addAllUnique",
- value: function (attr, items) {
- return this.set(attr, new _ParseOp.AddUniqueOp(items));
- }
- }, {
- key: "remove",
- value: function (attr, item) {
- return this.set(attr, new _ParseOp.RemoveOp([item]));
- }
- }, {
- key: "removeAll",
- value: function (attr, items) {
- return this.set(attr, new _ParseOp.RemoveOp(items));
- }
- }, {
- key: "op",
- value: function (attr) {
- var pending = this._getPendingOps();
- for (var i = pending.length; i--;) {
- if (pending[i][attr]) {
- return pending[i][attr];
- }
- }
- }
- }, {
- key: "clone",
- value: function clone() {
- var clone = new this.constructor(this.className);
- var attributes = this.attributes;
- if (typeof this.constructor.readOnlyAttributes === 'function') {
- var readonly = this.constructor.readOnlyAttributes() || [];
- var copy = {};
- for (var a in attributes) {
- if (readonly.indexOf(a) < 0) {
- copy[a] = attributes[a];
- }
- }
- attributes = copy;
- }
- if (clone.set) {
- clone.set(attributes);
- }
- return clone;
- }
- }, {
- key: "newInstance",
- value: function () {
- var clone = new this.constructor(this.className);
- clone.id = this.id;
- if (singleInstance) {
- return clone;
- }
- var stateController = _CoreManager.default.getObjectStateController();
- if (stateController) {
- stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier());
- }
- return clone;
- }
- }, {
- key: "isNew",
- value: function () {
- return !this.id;
- }
- }, {
- key: "existed",
- value: function () {
- if (!this.id) {
- return false;
- }
- var stateController = _CoreManager.default.getObjectStateController();
- var state = stateController.getState(this._getStateIdentifier());
- if (state) {
- return state.existed;
- }
- return false;
- }
- }, {
- key: "exists",
- value: function () {
- var _exists = (0, _asyncToGenerator2.default)(function* (options) {
- if (!this.id) {
- return false;
- }
- try {
- var ParseQuery = _CoreManager.default.getParseQuery();
- var query = new ParseQuery(this.className);
- yield query.get(this.id, options);
- return true;
- } catch (e) {
- if (e.code === _ParseError.default.OBJECT_NOT_FOUND) {
- return false;
- }
- throw e;
- }
- });
- function exists() {
- return _exists.apply(this, arguments);
- }
- return exists;
- }()
- }, {
- key: "isValid",
- value: function () {
- return !this.validate(this.attributes);
- }
- }, {
- key: "validate",
- value: function (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 (var key in attrs) {
- if (!/^[A-Za-z][0-9A-Za-z_.]*$/.test(key)) {
- return new _ParseError.default(_ParseError.default.INVALID_KEY_NAME);
- }
- }
- return false;
- }
- }, {
- key: "getACL",
- value: function () {
- var acl = this.get('ACL');
- if (acl instanceof _ParseACL.default) {
- return acl;
- }
- return null;
- }
- }, {
- key: "setACL",
- value: function (acl, options) {
- return this.set('ACL', acl, options);
- }
- }, {
- key: "revert",
- value: function () {
- var keysToRevert;
- for (var _len = arguments.length, keys = new Array(_len), _key = 0; _key < _len; _key++) {
- keys[_key] = arguments[_key];
- }
- if (keys.length) {
- keysToRevert = [];
- for (var 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);
- }
- }, {
- key: "clear",
- value: function () {
- var attributes = this.attributes;
- var erasable = {};
- var readonly = ['createdAt', 'updatedAt'];
- if (typeof this.constructor.readOnlyAttributes === 'function') {
- readonly = readonly.concat(this.constructor.readOnlyAttributes());
- }
- for (var attr in attributes) {
- if (readonly.indexOf(attr) < 0) {
- erasable[attr] = true;
- }
- }
- return this.set(erasable, {
- unset: true
- });
- }
- }, {
- key: "fetch",
- value: function (options) {
- options = options || {};
- var 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(function (key) {
- if (Array.isArray(key)) {
- fetchOptions.include = fetchOptions.include.concat(key);
- } else {
- fetchOptions.include.push(key);
- }
- });
- } else {
- fetchOptions.include.push(options.include);
- }
- }
- var controller = _CoreManager.default.getObjectController();
- return controller.fetch(this, true, fetchOptions);
- }
- }, {
- key: "fetchWithInclude",
- value: function (keys, options) {
- options = options || {};
- options.include = keys;
- return this.fetch(options);
- }
- }, {
- key: "saveEventually",
- value: function () {
- var _saveEventually = (0, _asyncToGenerator2.default)(function* (options) {
- try {
- yield this.save(null, options);
- } catch (e) {
- if (e.code === _ParseError.default.CONNECTION_FAILED) {
- yield _CoreManager.default.getEventuallyQueue().save(this, options);
- _CoreManager.default.getEventuallyQueue().poll();
- }
- }
- return this;
- });
- function saveEventually() {
- return _saveEventually.apply(this, arguments);
- }
- return saveEventually;
- }()
- }, {
- key: "save",
- value: function (arg1, arg2, arg3) {
- var _this = this;
- var attrs;
- var 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) {
- var validationError;
- options.error = function (_, validation) {
- validationError = validation;
- };
- var success = this.set(attrs, options);
- if (!success) {
- return Promise.reject(validationError);
- }
- }
- var 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;
- }
- var controller = _CoreManager.default.getObjectController();
- var unsaved = options.cascadeSave !== false ? (0, _unsavedChildren.default)(this) : null;
- return controller.save(unsaved, saveOptions).then(function () {
- return controller.save(_this, saveOptions);
- });
- }
- }, {
- key: "destroyEventually",
- value: function () {
- var _destroyEventually = (0, _asyncToGenerator2.default)(function* (options) {
- try {
- yield this.destroy(options);
- } catch (e) {
- if (e.code === _ParseError.default.CONNECTION_FAILED) {
- yield _CoreManager.default.getEventuallyQueue().destroy(this, options);
- _CoreManager.default.getEventuallyQueue().poll();
- }
- }
- return this;
- });
- function destroyEventually() {
- return _destroyEventually.apply(this, arguments);
- }
- return destroyEventually;
- }()
- }, {
- key: "destroy",
- value: function (options) {
- options = options || {};
- var 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);
- }
- }, {
- key: "pin",
- value: function () {
- return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
- }
- }, {
- key: "unPin",
- value: function () {
- return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
- }
- }, {
- key: "isPinned",
- value: function () {
- var _isPinned = (0, _asyncToGenerator2.default)(function* () {
- var localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- var objectKey = localDatastore.getKeyForObject(this);
- var pin = yield localDatastore.fromPinWithName(objectKey);
- return pin.length > 0;
- });
- function isPinned() {
- return _isPinned.apply(this, arguments);
- }
- return isPinned;
- }()
- }, {
- key: "pinWithName",
- value: function (name) {
- return ParseObject.pinAllWithName(name, [this]);
- }
- }, {
- key: "unPinWithName",
- value: function (name) {
- return ParseObject.unPinAllWithName(name, [this]);
- }
- }, {
- key: "fetchFromLocalDatastore",
- value: function () {
- var _fetchFromLocalDatastore = (0, _asyncToGenerator2.default)(function* () {
- var localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- throw new Error('Parse.enableLocalDatastore() must be called first');
- }
- var objectKey = localDatastore.getKeyForObject(this);
- var pinned = yield localDatastore._serializeObject(objectKey);
- if (!pinned) {
- throw new Error('Cannot fetch an unsaved ParseObject');
- }
- var result = ParseObject.fromJSON(pinned);
- this._finishFetch(result.toJSON());
- return this;
- });
- function fetchFromLocalDatastore() {
- return _fetchFromLocalDatastore.apply(this, arguments);
- }
- return fetchFromLocalDatastore;
- }()
- }], [{
- key: "_getClassMap",
- value: function () {
- return classMap;
- }
- }, {
- key: "_clearAllState",
- value: function () {
- var stateController = _CoreManager.default.getObjectStateController();
- stateController.clearAllState();
- }
- }, {
- key: "fetchAll",
- value: function (list) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var 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);
- }
- }, {
- key: "fetchAllWithInclude",
- value: function (list, keys, options) {
- options = options || {};
- options.include = keys;
- return ParseObject.fetchAll(list, options);
- }
- }, {
- key: "fetchAllIfNeededWithInclude",
- value: function (list, keys, options) {
- options = options || {};
- options.include = keys;
- return ParseObject.fetchAllIfNeeded(list, options);
- }
- }, {
- key: "fetchAllIfNeeded",
- value: function (list, options) {
- options = options || {};
- var 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);
- }
- }, {
- key: "handleIncludeOptions",
- value: function (options) {
- var include = [];
- if (Array.isArray(options.include)) {
- options.include.forEach(function (key) {
- if (Array.isArray(key)) {
- include = include.concat(key);
- } else {
- include.push(key);
- }
- });
- } else {
- include.push(options.include);
- }
- return include;
- }
- }, {
- key: "destroyAll",
- value: function (list) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var 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);
- }
- }, {
- key: "saveAll",
- value: function (list) {
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var 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);
- }
- }, {
- key: "createWithoutData",
- value: function (id) {
- var obj = new this();
- obj.id = id;
- return obj;
- }
- }, {
- key: "fromJSON",
- value: function (json, override, dirty) {
- if (!json.className) {
- throw new Error('Cannot create an object without a className');
- }
- var constructor = classMap[json.className];
- var o = constructor ? new constructor(json.className) : new ParseObject(json.className);
- var otherAttributes = {};
- for (var 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;
- }
- var 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;
- }
- }, {
- key: "registerSubclass",
- value: function (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;
- }
- }
- }, {
- key: "unregisterSubclass",
- value: function (className) {
- if (typeof className !== 'string') {
- throw new TypeError('The first argument must be a valid class name.');
- }
- delete classMap[className];
- }
- }, {
- key: "extend",
- value: function (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.");
- }
- }
- var adjustedClassName = className;
- if (adjustedClassName === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) {
- adjustedClassName = '_User';
- }
- var parentProto = ParseObject.prototype;
- if (this.hasOwnProperty('__super__') && this.__super__) {
- parentProto = this.prototype;
- }
- var ParseObjectSubclass = function (attributes, options) {
- this.className = adjustedClassName;
- this._objCount = objectCount++;
- if (typeof this.initialize === 'function') {
- this.initialize.apply(this, arguments);
- }
- if (this._initializers) {
- for (var 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 (var prop in protoProps) {
- if (prop === 'initialize') {
- Object.defineProperty(ParseObjectSubclass.prototype, '_initializers', {
- value: [].concat((0, _toConsumableArray2.default)(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 (var _prop in classProps) {
- if (_prop !== 'className') {
- Object.defineProperty(ParseObjectSubclass, _prop, {
- value: classProps[_prop],
- enumerable: false,
- writable: true,
- configurable: true
- });
- }
- }
- }
- classMap[adjustedClassName] = ParseObjectSubclass;
- return ParseObjectSubclass;
- }
- }, {
- key: "enableSingleInstance",
- value: function () {
- singleInstance = true;
- _CoreManager.default.setObjectStateController(SingleInstanceStateController);
- }
- }, {
- key: "disableSingleInstance",
- value: function () {
- singleInstance = false;
- _CoreManager.default.setObjectStateController(UniqueInstanceStateController);
- }
- }, {
- key: "pinAll",
- value: function (objects) {
- var localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
- }
- }, {
- key: "pinAllWithName",
- value: function (name, objects) {
- var localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return localDatastore._handlePinAllWithName(name, objects);
- }
- }, {
- key: "unPinAll",
- value: function (objects) {
- var localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
- }
- }, {
- key: "unPinAllWithName",
- value: function (name, objects) {
- var localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return localDatastore._handleUnPinAllWithName(name, objects);
- }
- }, {
- key: "unPinAllObjects",
- value: function () {
- var localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return localDatastore.unPinWithName(_LocalDatastoreUtils.DEFAULT_PIN);
- }
- }, {
- key: "unPinAllObjectsWithName",
- value: function (name) {
- var localDatastore = _CoreManager.default.getLocalDatastore();
- if (!localDatastore.isEnabled) {
- return Promise.reject('Parse.enableLocalDatastore() must be called first');
- }
- return localDatastore.unPinWithName(_LocalDatastoreUtils.PIN_PREFIX + name);
- }
- }]);
- }();
- var DefaultController = {
- fetch: function (target, forceFetch, options) {
- var localDatastore = _CoreManager.default.getLocalDatastore();
- if (Array.isArray(target)) {
- if (target.length < 1) {
- return Promise.resolve([]);
- }
- var objs = [];
- var ids = [];
- var className = null;
- var results = [];
- var error = null;
- target.forEach(function (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);
- }
- var ParseQuery = _CoreManager.default.getParseQuery();
- var 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(function () {
- var _ref = (0, _asyncToGenerator2.default)(function* (objects) {
- var idMap = {};
- objects.forEach(function (o) {
- idMap[o.id] = o;
- });
- for (var i = 0; i < objs.length; i++) {
- var 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 (var _i = 0; _i < results.length; _i++) {
- var _obj = results[_i];
- if (_obj && _obj.id && idMap[_obj.id]) {
- var id = _obj.id;
- _obj._finishFetch(idMap[id].toJSON());
- results[_i] = idMap[id];
- }
- }
- }
- for (var object of results) {
- yield localDatastore._updateObjectIfPinned(object);
- }
- return Promise.resolve(results);
- });
- return function () {
- return _ref.apply(this, arguments);
- };
- }());
- } 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'));
- }
- var RESTController = _CoreManager.default.getRESTController();
- var params = {};
- if (options && options.include) {
- params.include = options.include.join();
- }
- return RESTController.request('GET', 'classes/' + target.className + '/' + target._getId(), params, options).then(function () {
- var _ref2 = (0, _asyncToGenerator2.default)(function* (response) {
- target._clearPendingOps();
- target._clearServerData();
- target._finishFetch(response);
- yield localDatastore._updateObjectIfPinned(target);
- return target;
- });
- return function () {
- return _ref2.apply(this, arguments);
- };
- }());
- }
- return Promise.resolve(undefined);
- },
- destroy: function () {
- var _destroy = (0, _asyncToGenerator2.default)(function* (target, options) {
- var batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
- var localDatastore = _CoreManager.default.getLocalDatastore();
- var RESTController = _CoreManager.default.getRESTController();
- if (Array.isArray(target)) {
- if (target.length < 1) {
- return Promise.resolve([]);
- }
- var batches = [[]];
- target.forEach(function (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();
- }
- var deleteCompleted = Promise.resolve();
- var errors = [];
- batches.forEach(function (batch) {
- deleteCompleted = deleteCompleted.then(function () {
- return RESTController.request('POST', 'batch', {
- requests: batch.map(function (obj) {
- return {
- method: 'DELETE',
- path: getServerUrlPath() + 'classes/' + obj.className + '/' + obj._getId(),
- body: {}
- };
- })
- }, options).then(function (results) {
- for (var i = 0; i < results.length; i++) {
- if (results[i] && results[i].hasOwnProperty('error')) {
- var err = new _ParseError.default(results[i].error.code, results[i].error.error);
- err.object = batch[i];
- errors.push(err);
- }
- }
- });
- });
- });
- return deleteCompleted.then((0, _asyncToGenerator2.default)(function* () {
- if (errors.length) {
- var aggregate = new _ParseError.default(_ParseError.default.AGGREGATE_ERROR);
- aggregate.errors = errors;
- return Promise.reject(aggregate);
- }
- for (var object of target) {
- yield localDatastore._destroyObjectIfPinned(object);
- }
- return Promise.resolve(target);
- }));
- } else if (target instanceof ParseObject) {
- return RESTController.request('DELETE', 'classes/' + target.className + '/' + target._getId(), {}, options).then((0, _asyncToGenerator2.default)(function* () {
- yield localDatastore._destroyObjectIfPinned(target);
- return Promise.resolve(target);
- }));
- }
- return Promise.resolve(target);
- });
- function destroy() {
- return _destroy.apply(this, arguments);
- }
- return destroy;
- }(),
- save: function (target, options) {
- var batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE');
- var localDatastore = _CoreManager.default.getLocalDatastore();
- var mapIdForPin = {};
- var RESTController = _CoreManager.default.getRESTController();
- var stateController = _CoreManager.default.getObjectStateController();
- var 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([]);
- }
- var unsaved = target.concat();
- for (var i = 0; i < target.length; i++) {
- var target_i = target[i];
- if (target_i instanceof ParseObject) {
- unsaved = unsaved.concat((0, _unsavedChildren.default)(target_i, true));
- }
- }
- unsaved = (0, _unique.default)(unsaved);
- var filesSaved = [];
- var pending = [];
- unsaved.forEach(function (el) {
- if (el instanceof _ParseFile.default) {
- filesSaved.push(el.save(options));
- } else if (el instanceof ParseObject) {
- pending.push(el);
- }
- });
- return Promise.all(filesSaved).then(function () {
- var objectError = null;
- return (0, _promiseUtils.continueWhile)(function () {
- return pending.length > 0;
- }, function () {
- var batch = [];
- var nextPending = [];
- pending.forEach(function (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.'));
- }
- var batchReturned = (0, _promiseUtils.resolvingPromise)();
- var batchReady = [];
- var batchTasks = [];
- batch.forEach(function (obj, index) {
- var ready = (0, _promiseUtils.resolvingPromise)();
- batchReady.push(ready);
- var task = function task() {
- ready.resolve();
- return batchReturned.then(function (responses) {
- if (responses[index].hasOwnProperty('success')) {
- var objectId = responses[index].success.objectId;
- var 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')) {
- var serverError = responses[index].error;
- objectError = new _ParseError.default(serverError.code, serverError.error);
- pending = [];
- }
- obj._handleSaveError();
- }
- });
- };
- stateController.pushPendingState(obj._getStateIdentifier());
- batchTasks.push(stateController.enqueueTask(obj._getStateIdentifier(), task));
- });
- (0, _promiseUtils.when)(batchReady).then(function () {
- return RESTController.request('POST', 'batch', {
- requests: batch.map(function (obj) {
- var params = obj._getSaveParams();
- params.path = getServerUrlPath() + params.path;
- return params;
- })
- }, options);
- }).then(batchReturned.resolve, function (error) {
- batchReturned.reject(new _ParseError.default(_ParseError.default.INCORRECT_TYPE, error.message));
- });
- return (0, _promiseUtils.when)(batchTasks);
- }).then((0, _asyncToGenerator2.default)(function* () {
- if (objectError) {
- return Promise.reject(objectError);
- }
- for (var object of target) {
- if (object instanceof ParseObject) {
- yield localDatastore._updateLocalIdForObject(mapIdForPin[object.id], object);
- yield 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();
- var localId = target._localId;
- var targetCopy = target;
- var task = function task() {
- var params = targetCopy._getSaveParams();
- return RESTController.request(params.method, params.path, params.body, options).then(function (response) {
- var status = response._status;
- delete response._status;
- delete response._headers;
- delete response._xhr;
- targetCopy._handleSaveResponse(response, status);
- }, function (error) {
- targetCopy._handleSaveError();
- return Promise.reject(error);
- });
- };
- stateController.pushPendingState(target._getStateIdentifier());
- return stateController.enqueueTask(target._getStateIdentifier(), task).then((0, _asyncToGenerator2.default)(function* () {
- yield localDatastore._updateLocalIdForObject(localId, target);
- yield localDatastore._updateObjectIfPinned(target);
- return target;
- }), function (error) {
- return Promise.reject(error);
- });
- }
- return Promise.resolve(undefined);
- }
- };
- _CoreManager.default.setParseObject(ParseObject);
- _CoreManager.default.setObjectController(DefaultController);
- var _default = exports.default = ParseObject;
|