"use strict"; var _typeof3 = require("@babel/runtime-corejs3/helpers/typeof"); var _Object$keys2 = require("@babel/runtime-corejs3/core-js-stable/object/keys"); var _Object$getOwnPropertySymbols = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols"); var _filterInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/filter"); var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor"); var _forEachInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/for-each"); var _Object$getOwnPropertyDescriptors = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors"); var _Object$defineProperties = require("@babel/runtime-corejs3/core-js-stable/object/define-properties"); var _Object$defineProperty2 = require("@babel/runtime-corejs3/core-js-stable/object/define-property"); var _sliceInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/slice"); var _Array$from = require("@babel/runtime-corejs3/core-js-stable/array/from"); var _Symbol = require("@babel/runtime-corejs3/core-js-stable/symbol"); var _getIteratorMethod = require("@babel/runtime-corejs3/core-js/get-iterator-method"); var _Array$isArray2 = require("@babel/runtime-corejs3/core-js-stable/array/is-array"); var _WeakMap = require("@babel/runtime-corejs3/core-js-stable/weak-map"); var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault"); _Object$defineProperty2(exports, "__esModule", { value: true }); exports.default = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs3/regenerator")); var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/toConsumableArray")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/asyncToGenerator")); var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/typeof")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/createClass")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty")); var _indexOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/index-of")); var _freeze = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/freeze")); var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/keys")); var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/for-each")); var _stringify = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/json/stringify")); var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/includes")); var _getPrototypeOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/get-prototype-of")); var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat")); var _isArray = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/array/is-array")); var _promise = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/promise")); var _create = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/create")); var _defineProperty3 = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/define-property")); var _find = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find")); var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map")); 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 _EventuallyQueue = _interopRequireDefault(require("./EventuallyQueue")); 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 _ParseOp = require("./ParseOp"); var _ParseQuery = _interopRequireDefault(require("./ParseQuery")); 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(nodeInterop) { if (typeof _WeakMap !== "function") return null; var cacheBabelInterop = new _WeakMap(); var cacheNodeInterop = new _WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof3(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = _Object$defineProperty2 && _Object$getOwnPropertyDescriptor ? _Object$getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { _Object$defineProperty2(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof _Symbol !== "undefined" && _getIteratorMethod(o) || o["@@iterator"]; if (!it) { if (_Array$isArray2(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function () {}; return { s: F, n: function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function () { it = it.call(o); }, n: function () { var step = it.next(); normalCompletion = step.done; return step; }, e: function (_e2) { didErr = true; err = _e2; }, f: function () { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { var _context19; if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = _sliceInstanceProperty(_context19 = Object.prototype.toString.call(o)).call(_context19, 8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return _Array$from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function ownKeys(object, enumerableOnly) { var keys = _Object$keys2(object); if (_Object$getOwnPropertySymbols) { var symbols = _Object$getOwnPropertySymbols(object); enumerableOnly && (symbols = _filterInstanceProperty(symbols).call(symbols, function (sym) { return _Object$getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var _context17, _context18; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? _forEachInstanceProperty2(_context17 = ownKeys(Object(source), !0)).call(_context17, function (key) { (0, _defineProperty2.default)(target, key, source[key]); }) : _Object$getOwnPropertyDescriptors ? _Object$defineProperties(target, _Object$getOwnPropertyDescriptors(source)) : _forEachInstanceProperty2(_context18 = ownKeys(Object(source))).call(_context18, function (key) { _Object$defineProperty2(target, key, _Object$getOwnPropertyDescriptor(source, key)); }); } return target; } /** * @flow */ /*:: import type { AttributeMap, OpsMap } from './ObjectStateMutations';*/ /*:: import type { RequestOptions, FullOptions } from './RESTController';*/ var uuidv4 = require('./uuid'); /*:: export type Pointer = { __type: string, className: string, objectId: string, };*/ /*:: type SaveParams = { method: string, path: string, body: AttributeMap, };*/ /*:: export type SaveOptions = FullOptions & { cascadeSave?: boolean, context?: AttributeMap, };*/ // Mapping of class names to constructors, so we can populate objects from the // server with appropriate subclasses of ParseObject var classMap = {}; // Global counter for generating unique Ids for non-single-instance objects var objectCount = 0; // On web clients, objects are single-instance: any two objects with the same Id // will have the same attributes. However, this may be dangerous default // behavior in a server scenario 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((0, _indexOf.default)(url).call(url, '/')); } /** * Creates a new model with defined attributes. * *
You won't normally call this method directly. It is recommended that
* you use a subclass of Parse.Object instead, created by calling
* extend.
However, if you don't want to use a subclass, or aren't sure which * subclass is appropriate, you can use this form:
* var object = new Parse.Object("ClassName");
*
* That is basically equivalent to:
* var MyClass = Parse.Object.extend("ClassName");
* var object = new MyClass();
*
*
* @alias Parse.Object
*/
var ParseObject = /*#__PURE__*/function () {
/**
* @param {string} className The class name for the object
* @param {object} attributes The initial set of data to store in the object.
* @param {object} options The options for this object instance.
*/
function ParseObject(className /*: ?string | { className: string, [attr: string]: mixed }*/, attributes /*:: ?: { [attr: string]: mixed }*/, options /*:: ?: { ignoreValidation: boolean }*/) {
(0, _classCallCheck2.default)(this, ParseObject);
/**
* The ID of this object, unique within its class.
*
* @property {string} id
*/
(0, _defineProperty2.default)(this, "id", void 0);
(0, _defineProperty2.default)(this, "_localId", void 0);
(0, _defineProperty2.default)(this, "_objCount", void 0);
(0, _defineProperty2.default)(this, "className", void 0);
// Enable legacy initializers
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 && (0, _typeof2.default)(attributes) === 'object') {
toSet = attributes;
}
} else if (className && (0, _typeof2.default)(className) === 'object') {
this.className = className.className;
toSet = {};
for (var _attr in className) {
if (_attr !== 'className') {
toSet[_attr] = className[_attr];
}
}
if (attributes && (0, _typeof2.default)(attributes) === 'object') {
options = attributes;
}
}
if (toSet && !this.set(toSet, options)) {
throw new Error("Can't create an invalid Parse Object");
}
}
(0, _createClass2.default)(ParseObject, [{
key: "attributes",
get: /* Prototype getters / setters */
function () /*: AttributeMap*/{
var stateController = _CoreManager.default.getObjectStateController();
return (0, _freeze.default)(stateController.estimateAttributes(this._getStateIdentifier()));
}
/**
* The first time this object was saved on the server.
*
* @property {Date} createdAt
* @returns {Date}
*/
}, {
key: "createdAt",
get: function () /*: ?Date*/{
return this._getServerData().createdAt;
}
/**
* The last time this object was updated on the server.
*
* @property {Date} updatedAt
* @returns {Date}
*/
}, {
key: "updatedAt",
get: function () /*: ?Date*/{
return this._getServerData().updatedAt;
}
/* Private methods */
/**
* Returns a local or server Id used uniquely identify this object
*
* @returns {string}
*/
}, {
key: "_getId",
value: function () /*: string*/{
if (typeof this.id === 'string') {
return this.id;
}
if (typeof this._localId === 'string') {
return this._localId;
}
var localId = 'local' + uuidv4();
this._localId = localId;
return localId;
}
/**
* Returns a unique identifier used to pull data from the State Controller.
*
* @returns {Parse.Object|object}
*/
}, {
key: "_getStateIdentifier",
value: function () /*: ParseObject | { id: string, className: string }*/{
if (singleInstance) {
var id = this.id;
if (!id) {
id = this._getId();
}
return {
id: id,
className: this.className
};
} else {
return this;
}
}
}, {
key: "_getServerData",
value: function () /*: AttributeMap*/{
var stateController = _CoreManager.default.getObjectStateController();
return stateController.getServerData(this._getStateIdentifier());
}
}, {
key: "_clearServerData",
value: function () {
var serverData = this._getServerData();
var unset = {};
for (var _attr2 in serverData) {
unset[_attr2] = undefined;
}
var stateController = _CoreManager.default.getObjectStateController();
stateController.setServerData(this._getStateIdentifier(), unset);
}
}, {
key: "_getPendingOps",
value: function () /*: Arraytrue if the attribute contains a value that is not
* null or undefined.
*
* @param {string} attr The string name of the attribute.
* @returns {boolean}
*/
}, {
key: "has",
value: function (attr /*: string*/) /*: boolean*/{
var attributes = this.attributes;
if (attributes.hasOwnProperty(attr)) {
return attributes[attr] != null;
}
return false;
}
/**
* Sets a hash of model attributes on the object.
*
* You can call it with an object containing keys and values, with one * key and value, or dot notation. For example:
* gameTurn.set({
* player: player1,
* diceRoll: 2
* }, {
* error: function(gameTurnAgain, error) {
* // The set failed validation.
* }
* });
*
* game.set("currentPlayer", player2, {
* error: function(gameTurnAgain, error) {
* // The set failed validation.
* }
* });
*
* game.set("finished", true);
*
* game.set("player.score", 10);
*
* @param {(string|object)} key The key to set.
* @param {(string|object)} value The value to give it.
* @param {object} options A set of options for the set.
* The only supported option is error.
* @returns {(ParseObject|boolean)} true if the set succeeded.
*/
}, {
key: "set",
value: function (key /*: mixed*/, value /*: mixed*/, options /*:: ?: mixed*/) /*: ParseObject | boolean*/{
var changes = {};
var newOps = {};
if (key && (0, _typeof2.default)(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 = (0, _concat.default)(readonly).call(readonly, this.constructor.readOnlyAttributes());
}
for (var k in changes) {
if (k === 'createdAt' || k === 'updatedAt') {
// This property is read-only, but for legacy reasons we silently
// ignore it
continue;
}
if ((0, _indexOf.default)(readonly).call(readonly, 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] && (0, _typeof2.default)(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' && (0, _typeof2.default)(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;
// Calculate new values
var newValues = {};
for (var _attr9 in newOps) {
if (newOps[_attr9] instanceof _ParseOp.RelationOp) {
newValues[_attr9] = newOps[_attr9].applyTo(currentAttributes[_attr9], this, _attr9);
} else if (!(newOps[_attr9] instanceof _ParseOp.UnsetOp)) {
newValues[_attr9] = newOps[_attr9].applyTo(currentAttributes[_attr9]);
}
}
// Validate changes
if (!options.ignoreValidation) {
var validation = this.validate(newValues);
if (validation) {
if (typeof options.error === 'function') {
options.error(this, validation);
}
return false;
}
}
// Consolidate Ops
var pendingOps = this._getPendingOps();
var last = pendingOps.length - 1;
var stateController = _CoreManager.default.getObjectStateController();
for (var _attr10 in newOps) {
var nextOp = newOps[_attr10].mergeWith(pendingOps[last][_attr10]);
stateController.setPendingOp(this._getStateIdentifier(), _attr10, nextOp);
}
return this;
}
/**
* Remove an attribute from the model. This is a noop if the attribute doesn't
* exist.
*
* @param {string} attr The string name of an attribute.
* @param options
* @returns {(ParseObject | boolean)}
*/
}, {
key: "unset",
value: function (attr /*: string*/, options /*:: ?: { [opt: string]: mixed }*/) /*: ParseObject | boolean*/{
options = options || {};
options.unset = true;
return this.set(attr, null, options);
}
/**
* Atomically increments the value of the given attribute the next time the
* object is saved. If no amount is specified, 1 is used by default.
*
* @param attr {String} The key.
* @param amount {Number} The amount to increment by (optional).
* @returns {(ParseObject|boolean)}
*/
}, {
key: "increment",
value: function (attr /*: string*/, amount /*:: ?: number*/) /*: ParseObject | boolean*/{
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));
}
/**
* Atomically decrements the value of the given attribute the next time the
* object is saved. If no amount is specified, 1 is used by default.
*
* @param attr {String} The key.
* @param amount {Number} The amount to decrement by (optional).
* @returns {(ParseObject | boolean)}
*/
}, {
key: "decrement",
value: function (attr /*: string*/, amount /*:: ?: number*/) /*: ParseObject | boolean*/{
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));
}
/**
* Atomically add an object to the end of the array associated with a given
* key.
*
* @param attr {String} The key.
* @param item {} The item to add.
* @returns {(ParseObject | boolean)}
*/
}, {
key: "add",
value: function (attr /*: string*/, item /*: mixed*/) /*: ParseObject | boolean*/{
return this.set(attr, new _ParseOp.AddOp([item]));
}
/**
* Atomically add the objects to the end of the array associated with a given
* key.
*
* @param attr {String} The key.
* @param items {Object[]} The items to add.
* @returns {(ParseObject | boolean)}
*/
}, {
key: "addAll",
value: function (attr /*: string*/, items /*: ArrayParse.Object, in which case you can override this method
* to provide additional validation on set and
* save. Your implementation should return
*
* @param {object} attrs The current data to validate.
* @returns {Parse.Error|boolean} False if the data is valid. An error object otherwise.
* @see Parse.Object#set
*/
}, {
key: "validate",
value: function (attrs /*: AttributeMap*/) /*: ParseError | boolean*/{
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;
}
/**
* Returns the ACL for this object.
*
* @returns {Parse.ACL} An instance of Parse.ACL.
* @see Parse.Object#get
*/
}, {
key: "getACL",
value: function () /*: ?ParseACL*/{
var acl = this.get('ACL');
if (acl instanceof _ParseACL.default) {
return acl;
}
return null;
}
/**
* Sets the ACL to be used for this object.
*
* @param {Parse.ACL} acl An instance of Parse.ACL.
* @param {object} options
* @returns {(ParseObject | boolean)} Whether the set passed validation.
* @see Parse.Object#set
*/
}, {
key: "setACL",
value: function (acl /*: ParseACL*/, options /*:: ?: mixed*/) /*: ParseObject | boolean*/{
return this.set('ACL', acl, options);
}
/**
* Clears any (or specific) changes to this object made since the last call to save()
*
* @param {string} [keys] - specify which fields to revert
*/
}, {
key: "revert",
value: function () /*: void*/{
var keysToRevert;
for (var _len = arguments.length, keys = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
keys[_key2] = arguments[_key2];
}
if (keys.length) {
keysToRevert = [];
var _iterator = _createForOfIteratorHelper(keys),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _key3 = _step.value;
if (typeof _key3 === 'string') {
keysToRevert.push(_key3);
} else {
throw new Error('Parse.Object#revert expects either no, or a list of string, arguments.');
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
this._clearPendingOps(keysToRevert);
}
/**
* Clears all attributes on a model
*
* @returns {(ParseObject | boolean)}
*/
}, {
key: "clear",
value: function () /*: ParseObject | boolean*/{
var attributes = this.attributes;
var erasable = {};
var readonly = ['createdAt', 'updatedAt'];
if (typeof this.constructor.readOnlyAttributes === 'function') {
readonly = (0, _concat.default)(readonly).call(readonly, this.constructor.readOnlyAttributes());
}
for (var _attr11 in attributes) {
if ((0, _indexOf.default)(readonly).call(readonly, _attr11) < 0) {
erasable[_attr11] = true;
}
}
return this.set(erasable, {
unset: true
});
}
/**
* Fetch the model from the server. If the server's representation of the
* model differs from its current attributes, they will be overriden.
*
* @param {object} options
* Valid options are:
* object.save();
* or
* object.save(attrs);
* or
* object.save(null, options);
* or
* object.save(attrs, options);
* or
* object.save(key, value);
* or
* object.save(key, value, options);
*
* Example 1:
* gameTurn.save({
* player: "Jake Cutter",
* diceRoll: 2
* }).then(function(gameTurnAgain) {
* // The save was successful.
* }, function(error) {
* // The save failed. Error is an instance of Parse.Error.
* });
*
* Example 2:
* gameTurn.save("player", "Jake Cutter");
*
* @param {string | object | null} [arg1]
* Valid options are:
* await object.pin();
*
*
* To retrieve object:
* query.fromLocalDatastore() or query.fromPin()
*
* @returns {Promise} A promise that is fulfilled when the pin completes.
*/
}, {
key: "pin",
value: function () /*: Promise
* await object.unPin();
*
*
* @returns {Promise} A promise that is fulfilled when the unPin completes.
*/
}, {
key: "unPin",
value: function () /*: Promise
* const isPinned = await object.isPinned();
*
*
* @returns {Promise
* await object.pinWithName(name);
*
*
* To retrieve object:
* query.fromLocalDatastore() or query.fromPinWithName(name)
*
* @param {string} name Name of Pin.
* @returns {Promise} A promise that is fulfilled when the pin completes.
*/
}, {
key: "pinWithName",
value: function (name /*: string*/) /*: Promise
* await object.unPinWithName(name);
*
*
* @param {string} name Name of Pin.
* @returns {Promise} A promise that is fulfilled when the unPin completes.
*/
}, {
key: "unPinWithName",
value: function (name /*: string*/) /*: Promise
* await object.fetchFromLocalDatastore();
*
*
* You can create an unfetched pointer with Parse.Object.createWithoutData()
* and then call fetchFromLocalDatastore() on it.
*
* @returns {Promise} A promise that is fulfilled when the fetch completes.
*/
}, {
key: "fetchFromLocalDatastore",
value: function () {
var _fetchFromLocalDatastore = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee5() {
var localDatastore, objectKey, pinned, result;
return _regenerator.default.wrap(function (_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
localDatastore = _CoreManager.default.getLocalDatastore();
if (localDatastore.isEnabled) {
_context7.next = 3;
break;
}
throw new Error('Parse.enableLocalDatastore() must be called first');
case 3:
objectKey = localDatastore.getKeyForObject(this);
_context7.next = 6;
return localDatastore._serializeObject(objectKey);
case 6:
pinned = _context7.sent;
if (pinned) {
_context7.next = 9;
break;
}
throw new Error('Cannot fetch an unsaved ParseObject');
case 9:
result = ParseObject.fromJSON(pinned);
this._finishFetch(result.toJSON());
return _context7.abrupt("return", this);
case 12:
case "end":
return _context7.stop();
}
}, _callee5, this);
}));
function fetchFromLocalDatastore() {
return _fetchFromLocalDatastore.apply(this, arguments);
}
return fetchFromLocalDatastore;
}() /* Static methods */
}], [{
key: "_getClassMap",
value: function () {
return classMap;
}
}, {
key: "_clearAllState",
value: function () {
var stateController = _CoreManager.default.getObjectStateController();
stateController.clearAllState();
}
/**
* Fetches the given list of Parse.Object.
* If any error is encountered, stops and calls the error handler.
*
*
* Parse.Object.fetchAll([object1, object2, ...])
* .then((list) => {
* // All the objects were fetched.
* }, (error) => {
* // An error occurred while fetching one of the objects.
* });
*
*
* @param {Array} list A list of Parse.Object.
* @param {object} options
* Valid options are:
* Parse.Object.fetchAllWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
* .then((list) => {
* // All the objects were fetched.
* }, (error) => {
* // An error occurred while fetching one of the objects.
* });
*
*
* @param {Array} list A list of Parse.Object.
* @param {string | Array
* Parse.Object.fetchAllIfNeededWithInclude([object1, object2, ...], [pointer1, pointer2, ...])
* .then((list) => {
* // All the objects were fetched.
* }, (error) => {
* // An error occurred while fetching one of the objects.
* });
*
*
* @param {Array} list A list of Parse.Object.
* @param {string | Array
* Parse.Object.fetchAllIfNeeded([object1, ...])
* .then((list) => {
* // Objects were fetched and updated.
* }, (error) => {
* // An error occurred while fetching one of the objects.
* });
*
*
* @param {Array} list A list of Parse.Object.
* @param {object} options
* @static
* @returns {Parse.Object[]}
*/
}, {
key: "fetchAllIfNeeded",
value: function (list /*: ArrayUnlike saveAll, if an error occurs while deleting an individual model, * this method will continue trying to delete the rest of the models if * possible, except in the case of a fatal error like a connection error. * *
In particular, the Parse.Error object returned in the case of error may * be one of two types: * *
* Parse.Object.destroyAll([object1, object2, ...])
* .then((list) => {
* // All the objects were deleted.
* }, (error) => {
* // An error occurred while deleting one or more of the objects.
* // If this is an aggregate error, then we can inspect each error
* // object individually to determine the reason why a particular
* // object was not deleted.
* if (error.code === Parse.Error.AGGREGATE_ERROR) {
* for (var i = 0; i < error.errors.length; i++) {
* console.log("Couldn't delete " + error.errors[i].object.id +
* "due to " + error.errors[i].message);
* }
* } else {
* console.log("Delete aborted because of " + error.message);
* }
* });
*
*
* @param {Array} list A list of Parse.Object.
* @param {object} options
* @static
* @returns {Promise} A promise that is fulfilled when the destroyAll
* completes.
*/
}, {
key: "destroyAll",
value: function (list /*: Array
* Parse.Object.saveAll([object1, object2, ...])
* .then((list) => {
* // All the objects were saved.
* }, (error) => {
* // An error occurred while saving one of the objects.
* });
*
*
* @param {Array} list A list of Parse.Object.
* @param {object} options
* @static
* @returns {Parse.Object[]}
*/
}, {
key: "saveAll",
value: function (list /*: ArrayA shortcut for:
* var Foo = Parse.Object.extend("Foo");
* var pointerToFoo = new Foo();
* pointerToFoo.id = "myObjectId";
*
*
* @param {string} id The ID of the object to create a reference to.
* @static
* @returns {Parse.Object} A Parse.Object reference.
*/
}, {
key: "createWithoutData",
value: function (id /*: string*/) {
var obj = new this();
obj.id = id;
return obj;
}
/**
* Creates a new instance of a Parse Object from a JSON representation.
*
* @param {object} json The JSON map of the Object's data
* @param {boolean} override In single instance mode, all old server data
* is overwritten if this is set to true
* @param {boolean} dirty Whether the Parse.Object should set JSON keys to dirty
* @static
* @returns {Parse.Object} A Parse.Object reference
*/
}, {
key: "fromJSON",
value: function (json /*: any*/, override /*:: ?: boolean*/, dirty /*:: ?: boolean*/) {
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 _attr12 in json) {
if (_attr12 !== 'className' && _attr12 !== '__type') {
otherAttributes[_attr12] = json[_attr12];
if (dirty) {
o.set(_attr12, json[_attr12]);
}
}
}
if (override) {
// id needs to be set before clearServerData can work
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;
}
/**
* Registers a subclass of Parse.Object with a specific class name.
* When objects of that class are retrieved from a query, they will be
* instantiated with this subclass.
* This is only necessary when using ES6 subclassing.
*
* @param {string} className The class name of the subclass
* @param {Function} constructor The subclass
*/
}, {
key: "registerSubclass",
value: function (className /*: string*/, constructor /*: any*/) {
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
*/
}, {
key: "unregisterSubclass",
value: function (className /*: string*/) {
if (typeof className !== 'string') {
throw new TypeError('The first argument must be a valid class name.');
}
delete classMap[className];
}
/**
* Creates a new subclass of Parse.Object for the given Parse class name.
*
* Every extension of a Parse class will inherit from the most recent * previous extension of that class. When a Parse.Object is automatically * created by parsing JSON, it will use the most recent extension of that * class.
* *You should call either:
* var MyClass = Parse.Object.extend("MyClass", {
* Instance methods,
* initialize: function(attrs, options) {
* this.someInstanceProperty = [],
* Other instance properties
* }
* }, {
* Class properties
* });
* or, for Backbone compatibility:
* var MyClass = Parse.Object.extend({
* className: "MyClass",
* Instance methods,
* initialize: function(attrs, options) {
* this.someInstanceProperty = [],
* Other instance properties
* }
* }, {
* Class properties
* });
*
* @param {string} className The name of the Parse class backing this model.
* @param {object} protoProps Instance properties to add to instances of the
* class returned from this method.
* @param {object} classProps Class properties to add the class returned from
* this method.
* @returns {Parse.Object} A new subclass of Parse.Object.
*/
}, {
key: "extend",
value: function (className /*: any*/, protoProps /*: any*/, classProps /*: any*/) {
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++;
// Enable legacy initializers
if (typeof this.initialize === 'function') {
this.initialize.apply(this, arguments);
}
if (this._initializers) {
var _iterator2 = _createForOfIteratorHelper(this._initializers),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var initializer = _step2.value;
initializer.apply(this, arguments);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
if (attributes && (0, _typeof2.default)(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 = (0, _create.default)(parentProto, {
constructor: {
value: ParseObjectSubclass,
enumerable: false,
writable: true,
configurable: true
}
});
}
if (protoProps) {
for (var prop in protoProps) {
if (prop === 'initialize') {
var _context9;
(0, _defineProperty3.default)(ParseObjectSubclass.prototype, '_initializers', {
value: (0, _concat.default)(_context9 = []).call(_context9, (0, _toConsumableArray2.default)(ParseObjectSubclass.prototype._initializers || []), [protoProps[prop]]),
enumerable: false,
writable: true,
configurable: true
});
continue;
}
if (prop !== 'className') {
(0, _defineProperty3.default)(ParseObjectSubclass.prototype, prop, {
value: protoProps[prop],
enumerable: false,
writable: true,
configurable: true
});
}
}
}
if (classProps) {
for (var _prop in classProps) {
if (_prop !== 'className') {
(0, _defineProperty3.default)(ParseObjectSubclass, _prop, {
value: classProps[_prop],
enumerable: false,
writable: true,
configurable: true
});
}
}
}
classMap[adjustedClassName] = ParseObjectSubclass;
return ParseObjectSubclass;
}
/**
* Enable single instance objects, where any local objects with the same Id
* share the same attributes, and stay synchronized with each other.
* This is disabled by default in server environments, since it can lead to
* security issues.
*
* @static
*/
}, {
key: "enableSingleInstance",
value: function () {
singleInstance = true;
_CoreManager.default.setObjectStateController(SingleInstanceStateController);
}
/**
* Disable single instance objects, where any local objects with the same Id
* share the same attributes, and stay synchronized with each other.
* When disabled, you can have two instances of the same object in memory
* without them sharing attributes.
*
* @static
*/
}, {
key: "disableSingleInstance",
value: function () {
singleInstance = false;
_CoreManager.default.setObjectStateController(UniqueInstanceStateController);
}
/**
* Asynchronously stores the objects and every object they point to in the local datastore,
* recursively, using a default pin name: _default.
*
* If those other objects have not been fetched from Parse, they will not be stored.
* However, if they have changed data, all the changes will be retained.
*
*
* await Parse.Object.pinAll([...]);
*
*
* To retrieve object:
* query.fromLocalDatastore() or query.fromPin()
*
* @param {Array} objects A list of Parse.Object.
* @returns {Promise} A promise that is fulfilled when the pin completes.
* @static
*/
}, {
key: "pinAll",
value: function (objects /*: Array
* await Parse.Object.pinAllWithName(name, [obj1, obj2, ...]);
*
*
* To retrieve object:
* query.fromLocalDatastore() or query.fromPinWithName(name)
*
* @param {string} name Name of Pin.
* @param {Array} objects A list of Parse.Object.
* @returns {Promise} A promise that is fulfilled when the pin completes.
* @static
*/
}, {
key: "pinAllWithName",
value: function (name /*: string*/, objects /*: Array
* await Parse.Object.unPinAll([...]);
*
*
* @param {Array} objects A list of Parse.Object.
* @returns {Promise} A promise that is fulfilled when the unPin completes.
* @static
*/
}, {
key: "unPinAll",
value: function (objects /*: Array
* await Parse.Object.unPinAllWithName(name, [obj1, obj2, ...]);
*
*
* @param {string} name Name of Pin.
* @param {Array} objects A list of Parse.Object.
* @returns {Promise} A promise that is fulfilled when the unPin completes.
* @static
*/
}, {
key: "unPinAllWithName",
value: function (name /*: string*/, objects /*: Array
* await Parse.Object.unPinAllObjects();
*
*
* @returns {Promise} A promise that is fulfilled when the unPin completes.
* @static
*/
}, {
key: "unPinAllObjects",
value: function () /*: Promise
* await Parse.Object.unPinAllObjectsWithName(name);
*
*
* @param {string} name Name of Pin.
* @returns {Promise} A promise that is fulfilled when the unPin completes.
* @static
*/
}, {
key: "unPinAllObjectsWithName",
value: function (name /*: string*/) /*: Promise