"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _CoreManager = _interopRequireDefault(require("./CoreManager")); var _canBeSerialized = _interopRequireDefault(require("./canBeSerialized")); var _decode = _interopRequireDefault(require("./decode")); var _encode = _interopRequireDefault(require("./encode")); var _escape = _interopRequireDefault(require("./escape")); var _ParseACL = _interopRequireDefault(require("./ParseACL")); var _parseDate = _interopRequireDefault(require("./parseDate")); var _ParseError = _interopRequireDefault(require("./ParseError")); var _ParseFile = _interopRequireDefault(require("./ParseFile")); var _promiseUtils = require("./promiseUtils"); var _LocalDatastoreUtils = require("./LocalDatastoreUtils"); var _uuid = _interopRequireDefault(require("./uuid")); var _ParseOp = require("./ParseOp"); var _ParseRelation = _interopRequireDefault(require("./ParseRelation")); var SingleInstanceStateController = _interopRequireWildcard(require("./SingleInstanceStateController")); var _unique = _interopRequireDefault(require("./unique")); var UniqueInstanceStateController = _interopRequireWildcard(require("./UniqueInstanceStateController")); var _unsavedChildren = _interopRequireDefault(require("./unsavedChildren")); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } // Mapping of class names to constructors, so we can populate objects from the // server with appropriate subclasses of ParseObject const classMap = {}; // Global counter for generating unique Ids for non-single-instance objects let 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 let singleInstance = !_CoreManager.default.get('IS_NODE'); if (singleInstance) { _CoreManager.default.setObjectStateController(SingleInstanceStateController); } else { _CoreManager.default.setObjectStateController(UniqueInstanceStateController); } function getServerUrlPath() { let serverUrl = _CoreManager.default.get('SERVER_URL'); if (serverUrl[serverUrl.length - 1] !== '/') { serverUrl += '/'; } const url = serverUrl.replace(/https?:\/\//, ''); return url.substr(url.indexOf('/')); } /** * 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 */ class ParseObject { /** * @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. * @param {boolean} [options.ignoreValidation] Set to `true` ignore any attribute validation errors. */ constructor(className, attributes, options) { // Enable legacy initializers if (typeof this.initialize === 'function') { this.initialize.apply(this, arguments); } let toSet = null; this._objCount = objectCount++; if (typeof className === 'string') { this.className = className; if (attributes && typeof attributes === 'object') { toSet = attributes; } } else if (className && typeof className === 'object') { this.className = className.className; toSet = {}; for (const attr in className) { if (attr !== 'className') { toSet[attr] = className[attr]; } } if (attributes && typeof attributes === 'object') { options = attributes; } } if (toSet && !this.set(toSet, options)) { throw new Error("Can't create an invalid Parse Object"); } } /** * The ID of this object, unique within its class. * * @property {string} id */ /* Prototype getters / setters */ get attributes() { const stateController = _CoreManager.default.getObjectStateController(); return Object.freeze(stateController.estimateAttributes(this._getStateIdentifier())); } /** * The first time this object was saved on the server. * * @property {Date} createdAt * @returns {Date} */ get createdAt() { return this._getServerData().createdAt; } /** * The last time this object was updated on the server. * * @property {Date} updatedAt * @returns {Date} */ get updatedAt() { return this._getServerData().updatedAt; } /* Private methods */ /** * Returns a local or server Id used uniquely identify this object * * @returns {string} */ _getId() { if (typeof this.id === 'string') { return this.id; } if (typeof this._localId === 'string') { return this._localId; } const localId = 'local' + (0, _uuid.default)(); this._localId = localId; return localId; } /** * Returns a unique identifier used to pull data from the State Controller. * * @returns {Parse.Object|object} */ _getStateIdentifier() { if (singleInstance) { let id = this.id; if (!id) { id = this._getId(); } return { id: id, className: this.className }; } else { return this; } } _getServerData() { const stateController = _CoreManager.default.getObjectStateController(); return stateController.getServerData(this._getStateIdentifier()); } _clearServerData() { const serverData = this._getServerData(); const unset = {}; for (const attr in serverData) { unset[attr] = undefined; } const stateController = _CoreManager.default.getObjectStateController(); stateController.setServerData(this._getStateIdentifier(), unset); } _getPendingOps() { const stateController = _CoreManager.default.getObjectStateController(); return stateController.getPendingOps(this._getStateIdentifier()); } /** * @param {Array
true
if the attribute contains a value that is not
* null or undefined.
*
* @param {string} attr The string name of the attribute.
* @returns {boolean}
*/
has(attr) {
const 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.
*/
set(key, value, options) {
let changes = {};
const newOps = {};
if (key && typeof key === 'object') {
changes = key;
options = value;
} else if (typeof key === 'string') {
changes[key] = value;
} else {
return this;
}
options = options || {};
let readonly = [];
if (typeof this.constructor.readOnlyAttributes === 'function') {
readonly = readonly.concat(this.constructor.readOnlyAttributes());
}
for (const k in changes) {
if (k === 'createdAt' || k === 'updatedAt') {
// This property is read-only, but for legacy reasons we silently
// ignore it
continue;
}
if (readonly.indexOf(k) > -1) {
throw new Error('Cannot modify readonly attribute: ' + k);
}
if (options.unset) {
newOps[k] = new _ParseOp.UnsetOp();
} else if (changes[k] instanceof _ParseOp.Op) {
newOps[k] = changes[k];
} else if (changes[k] && typeof changes[k] === 'object' && typeof changes[k].__op === 'string') {
newOps[k] = (0, _ParseOp.opFromJSON)(changes[k]);
} else if (k === 'objectId' || k === 'id') {
if (typeof changes[k] === 'string') {
this.id = changes[k];
}
} else if (k === 'ACL' && typeof changes[k] === 'object' && !(changes[k] instanceof _ParseACL.default)) {
newOps[k] = new _ParseOp.SetOp(new _ParseACL.default(changes[k]));
} else if (changes[k] instanceof _ParseRelation.default) {
const relation = new _ParseRelation.default(this, k);
relation.targetClassName = changes[k].targetClassName;
newOps[k] = new _ParseOp.SetOp(relation);
} else {
newOps[k] = new _ParseOp.SetOp(changes[k]);
}
}
const currentAttributes = this.attributes;
// Calculate new values
const newValues = {};
for (const attr in newOps) {
if (newOps[attr] instanceof _ParseOp.RelationOp) {
newValues[attr] = newOps[attr].applyTo(currentAttributes[attr], this, attr);
} else if (!(newOps[attr] instanceof _ParseOp.UnsetOp)) {
newValues[attr] = newOps[attr].applyTo(currentAttributes[attr]);
}
}
// Validate changes
if (!options.ignoreValidation) {
const validation = this.validate(newValues);
if (validation) {
if (typeof options.error === 'function') {
options.error(this, validation);
}
return false;
}
}
// Consolidate Ops
const pendingOps = this._getPendingOps();
const last = pendingOps.length - 1;
const stateController = _CoreManager.default.getObjectStateController();
for (const attr in newOps) {
const nextOp = newOps[attr].mergeWith(pendingOps[last][attr]);
stateController.setPendingOp(this._getStateIdentifier(), attr, nextOp);
}
return this;
}
/**
* 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)}
*/
unset(attr, options) {
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)}
*/
increment(attr, amount) {
if (typeof amount === 'undefined') {
amount = 1;
}
if (typeof amount !== 'number') {
throw new Error('Cannot increment by a non-numeric amount.');
}
return this.set(attr, new _ParseOp.IncrementOp(amount));
}
/**
* 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)}
*/
decrement(attr, amount) {
if (typeof amount === 'undefined') {
amount = 1;
}
if (typeof amount !== 'number') {
throw new Error('Cannot decrement by a non-numeric amount.');
}
return this.set(attr, new _ParseOp.IncrementOp(amount * -1));
}
/**
* 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)}
*/
add(attr, item) {
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)}
*/
addAll(attr, items) {
return this.set(attr, new _ParseOp.AddOp(items));
}
/**
* Atomically add an object to the array associated with a given key, only
* if it is not already present in the array. The position of the insert is
* not guaranteed.
*
* @param attr {String} The key.
* @param item {} The object to add.
* @returns {(ParseObject | boolean)}
*/
addUnique(attr, item) {
return this.set(attr, new _ParseOp.AddUniqueOp([item]));
}
/**
* Atomically add the objects to the array associated with a given key, only
* if it is not already present in the array. The position of the insert is
* not guaranteed.
*
* @param attr {String} The key.
* @param items {Object[]} The objects to add.
* @returns {(ParseObject | boolean)}
*/
addAllUnique(attr, items) {
return this.set(attr, new _ParseOp.AddUniqueOp(items));
}
/**
* Atomically remove all instances of an object from the array associated
* with a given key.
*
* @param attr {String} The key.
* @param item {} The object to remove.
* @returns {(ParseObject | boolean)}
*/
remove(attr, item) {
return this.set(attr, new _ParseOp.RemoveOp([item]));
}
/**
* Atomically remove all instances of the objects from the array associated
* with a given key.
*
* @param attr {String} The key.
* @param items {Object[]} The object to remove.
* @returns {(ParseObject | boolean)}
*/
removeAll(attr, items) {
return this.set(attr, new _ParseOp.RemoveOp(items));
}
/**
* Returns an instance of a subclass of Parse.Op describing what kind of
* modification has been performed on this field since the last time it was
* saved. For example, after calling object.increment("x"), calling
* object.op("x") would return an instance of Parse.Op.Increment.
*
* @param attr {String} The key.
* @returns {Parse.Op | undefined} The operation, or undefined if none.
*/
op(attr) {
const pending = this._getPendingOps();
for (let i = pending.length; i--;) {
if (pending[i][attr]) {
return pending[i][attr];
}
}
}
/**
* Creates a new model with identical attributes to this one.
*
* @returns {Parse.Object}
*/
clone() {
const clone = new this.constructor(this.className);
let attributes = this.attributes;
if (typeof this.constructor.readOnlyAttributes === 'function') {
const readonly = this.constructor.readOnlyAttributes() || [];
// Attributes are frozen, so we have to rebuild an object,
// rather than delete readonly keys
const copy = {};
for (const a in attributes) {
if (readonly.indexOf(a) < 0) {
copy[a] = attributes[a];
}
}
attributes = copy;
}
if (clone.set) {
clone.set(attributes);
}
return clone;
}
/**
* Creates a new instance of this object. Not to be confused with clone()
*
* @returns {Parse.Object}
*/
newInstance() {
const clone = new this.constructor(this.className);
clone.id = this.id;
if (singleInstance) {
// Just return an object with the right id
return clone;
}
const stateController = _CoreManager.default.getObjectStateController();
if (stateController) {
stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier());
}
return clone;
}
/**
* Returns true if this object has never been saved to Parse.
*
* @returns {boolean}
*/
isNew() {
return !this.id;
}
/**
* Returns true if this object was created by the Parse server when the
* object might have already been there (e.g. in the case of a Facebook
* login)
*
* @returns {boolean}
*/
existed() {
if (!this.id) {
return false;
}
const stateController = _CoreManager.default.getObjectStateController();
const state = stateController.getState(this._getStateIdentifier());
if (state) {
return state.existed;
}
return false;
}
/**
* Returns true if this object exists on the Server
*
* @param {object} options
* Valid options are:Parse.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
*/
validate(attrs) {
if (attrs.hasOwnProperty('ACL') && !(attrs.ACL instanceof _ParseACL.default)) {
return new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'ACL must be a Parse ACL.');
}
for (const key in attrs) {
if (!/^[A-Za-z][0-9A-Za-z_.]*$/.test(key)) {
return new _ParseError.default(_ParseError.default.INVALID_KEY_NAME);
}
}
return false;
}
/**
* Returns the ACL for this object.
*
* @returns {Parse.ACL|null} An instance of Parse.ACL.
* @see Parse.Object#get
*/
getACL() {
const 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
*/
setACL(acl, options) {
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
*/
revert(...keys) {
let keysToRevert;
if (keys.length) {
keysToRevert = [];
for (const key of keys) {
if (typeof key === 'string') {
keysToRevert.push(key);
} else {
throw new Error('Parse.Object#revert expects either no, or a list of string, arguments.');
}
}
}
this._clearPendingOps(keysToRevert);
}
/**
* Clears all attributes on a model
*
* @returns {(ParseObject | boolean)}
*/
clear() {
const attributes = this.attributes;
const erasable = {};
let readonly = ['createdAt', 'updatedAt'];
if (typeof this.constructor.readOnlyAttributes === 'function') {
readonly = readonly.concat(this.constructor.readOnlyAttributes());
}
for (const attr in attributes) {
if (readonly.indexOf(attr) < 0) {
erasable[attr] = true;
}
}
return this.set(erasable, {
unset: true
});
}
/**
* Fetch 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.
*/
pin() {
return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]);
}
/**
* Asynchronously removes the object and every object it points to in the local datastore,
* recursively, using a default pin name: _default.
*
* * await object.unPin(); ** * @returns {Promise} A promise that is fulfilled when the unPin completes. */ unPin() { return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, [this]); } /** * Asynchronously returns if the object is pinned * *
* 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.
*/
pinWithName(name) {
return ParseObject.pinAllWithName(name, [this]);
}
/**
* Asynchronously removes the object and every object it points to in the local datastore, recursively.
*
* * await object.unPinWithName(name); ** * @param {string} name Name of Pin. * @returns {Promise} A promise that is fulfilled when the unPin completes. */ unPinWithName(name) { return ParseObject.unPinAllWithName(name, [this]); } /** * Asynchronously loads data from the local datastore into this object. * *
* 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.
*/
async fetchFromLocalDatastore() {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
throw new Error('Parse.enableLocalDatastore() must be called first');
}
const objectKey = localDatastore.getKeyForObject(this);
const pinned = await localDatastore._serializeObject(objectKey);
if (!pinned) {
throw new Error('Cannot fetch an unsaved ParseObject');
}
const result = ParseObject.fromJSON(pinned);
this._finishFetch(result.toJSON());
return this;
}
/* Static methods */
static _clearAllState() {
const 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[]}
*/
static fetchAllIfNeeded(list, options) {
options = options || {};
const queryOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
queryOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
queryOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('include')) {
queryOptions.include = ParseObject.handleIncludeOptions(options);
}
return _CoreManager.default.getObjectController().fetch(list, false, queryOptions);
}
static handleIncludeOptions(options) {
let include = [];
if (Array.isArray(options.include)) {
options.include.forEach(key => {
if (Array.isArray(key)) {
include = include.concat(key);
} else {
include.push(key);
}
});
} else {
include.push(options.include);
}
return include;
}
/**
* Destroy the given list of models on the server if it was already persisted.
*
* Unlike 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.
*/
static destroyAll(list, options = {}) {
const destroyOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
destroyOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
destroyOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
destroyOptions.batchSize = options.batchSize;
}
if (options.hasOwnProperty('context') && typeof options.context === 'object') {
destroyOptions.context = options.context;
}
return _CoreManager.default.getObjectController().destroy(list, destroyOptions);
}
/**
* Saves the given list of Parse.Object.
* If any error is encountered, stops and calls the error handler.
*
* * 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[]}
*/
static saveAll(list, options = {}) {
const saveOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
saveOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
saveOptions.sessionToken = options.sessionToken;
}
if (options.hasOwnProperty('batchSize') && typeof options.batchSize === 'number') {
saveOptions.batchSize = options.batchSize;
}
if (options.hasOwnProperty('context') && typeof options.context === 'object') {
saveOptions.context = options.context;
}
return _CoreManager.default.getObjectController().save(list, saveOptions);
}
/**
* Creates a reference to a subclass of Parse.Object with the given id. This
* does not exist on Parse.Object, only on subclasses.
*
* A 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. */ static createWithoutData(id) { const 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 */ static fromJSON(json, override, dirty) { if (!json.className) { throw new Error('Cannot create an object without a className'); } const constructor = classMap[json.className]; const o = constructor ? new constructor(json.className) : new ParseObject(json.className); const otherAttributes = {}; for (const attr in json) { if (attr !== 'className' && attr !== '__type') { otherAttributes[attr] = json[attr]; if (dirty) { o.set(attr, json[attr]); } } } if (override) { // id needs to be set before clearServerData can work if (otherAttributes.objectId) { o.id = otherAttributes.objectId; } let preserved = null; if (typeof o._preserveFieldsOnFetch === 'function') { preserved = o._preserveFieldsOnFetch(); } o._clearServerData(); if (preserved) { o._finishFetch(preserved); } } o._finishFetch(otherAttributes); if (json.objectId) { o._setExisted(true); } return o; } /** * 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 */ static registerSubclass(className, constructor) { if (typeof className !== 'string') { throw new TypeError('The first argument must be a valid class name.'); } if (typeof constructor === 'undefined') { throw new TypeError('You must supply a subclass constructor.'); } if (typeof constructor !== 'function') { throw new TypeError('You must register the subclass constructor. ' + 'Did you attempt to register an instance of the subclass?'); } classMap[className] = constructor; if (!constructor.className) { constructor.className = className; } } /** * Unegisters a subclass of Parse.Object with a specific class name. * * @param {string} className The class name of the subclass */ static unregisterSubclass(className) { if (typeof className !== 'string') { throw new TypeError('The first argument must be a valid class name.'); } delete classMap[className]; } /** * 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. */ static extend(className, protoProps, classProps) { if (typeof className !== 'string') { if (className && typeof className.className === 'string') { return ParseObject.extend(className.className, className, protoProps); } else { throw new Error("Parse.Object.extend's first argument should be the className."); } } let adjustedClassName = className; if (adjustedClassName === 'User' && _CoreManager.default.get('PERFORM_USER_REWRITE')) { adjustedClassName = '_User'; } let parentProto = ParseObject.prototype; if (this.hasOwnProperty('__super__') && this.__super__) { parentProto = this.prototype; } let ParseObjectSubclass = function (attributes, options) { this.className = adjustedClassName; this._objCount = objectCount++; // Enable legacy initializers if (typeof this.initialize === 'function') { this.initialize.apply(this, arguments); } if (this._initializers) { for (const initializer of this._initializers) { initializer.apply(this, arguments); } } if (attributes && typeof attributes === 'object') { if (!this.set(attributes || {}, options)) { throw new Error("Can't create an invalid Parse Object"); } } }; if (classMap[adjustedClassName]) { ParseObjectSubclass = classMap[adjustedClassName]; } else { ParseObjectSubclass.extend = function (name, protoProps, classProps) { if (typeof name === 'string') { return ParseObject.extend.call(ParseObjectSubclass, name, protoProps, classProps); } return ParseObject.extend.call(ParseObjectSubclass, adjustedClassName, name, protoProps); }; ParseObjectSubclass.createWithoutData = ParseObject.createWithoutData; ParseObjectSubclass.className = adjustedClassName; ParseObjectSubclass.__super__ = parentProto; ParseObjectSubclass.prototype = Object.create(parentProto, { constructor: { value: ParseObjectSubclass, enumerable: false, writable: true, configurable: true } }); } if (protoProps) { for (const prop in protoProps) { if (prop === 'initialize') { Object.defineProperty(ParseObjectSubclass.prototype, '_initializers', { value: [...(ParseObjectSubclass.prototype._initializers || []), protoProps[prop]], enumerable: false, writable: true, configurable: true }); continue; } if (prop !== 'className') { Object.defineProperty(ParseObjectSubclass.prototype, prop, { value: protoProps[prop], enumerable: false, writable: true, configurable: true }); } } } if (classProps) { for (const prop in classProps) { if (prop !== 'className') { Object.defineProperty(ParseObjectSubclass, prop, { value: classProps[prop], enumerable: false, writable: true, configurable: true }); } } } classMap[adjustedClassName] = ParseObjectSubclass; return ParseObjectSubclass; } /** * 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 */ static enableSingleInstance() { 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 */ static disableSingleInstance() { 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
*/
static pinAll(objects) {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
return Promise.reject('Parse.enableLocalDatastore() must be called first');
}
return ParseObject.pinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
}
/**
* Asynchronously stores the objects and every object they point to in the local datastore, recursively.
*
* 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.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
*/
static pinAllWithName(name, objects) {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
return Promise.reject('Parse.enableLocalDatastore() must be called first');
}
return localDatastore._handlePinAllWithName(name, objects);
}
/**
* Asynchronously removes the objects and every object they point to in the local datastore,
* recursively, using a default pin name: _default.
*
* * await Parse.Object.unPinAll([...]); ** * @param {Array} objects A list of
Parse.Object
.
* @returns {Promise} A promise that is fulfilled when the unPin completes.
* @static
*/
static unPinAll(objects) {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
return Promise.reject('Parse.enableLocalDatastore() must be called first');
}
return ParseObject.unPinAllWithName(_LocalDatastoreUtils.DEFAULT_PIN, objects);
}
/**
* Asynchronously removes the objects and every object they point to in the local datastore, recursively.
*
* * 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
*/
static unPinAllWithName(name, objects) {
const localDatastore = _CoreManager.default.getLocalDatastore();
if (!localDatastore.isEnabled) {
return Promise.reject('Parse.enableLocalDatastore() must be called first');
}
return localDatastore._handleUnPinAllWithName(name, objects);
}
/**
* Asynchronously removes all objects in the local datastore using a default pin name: _default.
*
* * await Parse.Object.unPinAllObjects(); ** * @returns {Promise} A promise that is fulfilled when the unPin completes. * @static */ static unPinAllObjects() { const localDatastore = _CoreManager.default.getLocalDatastore(); if (!localDatastore.isEnabled) { return Promise.reject('Parse.enableLocalDatastore() must be called first'); } return localDatastore.unPinWithName(_LocalDatastoreUtils.DEFAULT_PIN); } /** * Asynchronously removes all objects with the specified pin name. * Deletes the pin name also. * *
* await Parse.Object.unPinAllObjectsWithName(name); ** * @param {string} name Name of Pin. * @returns {Promise} A promise that is fulfilled when the unPin completes. * @static */ static unPinAllObjectsWithName(name) { const localDatastore = _CoreManager.default.getLocalDatastore(); if (!localDatastore.isEnabled) { return Promise.reject('Parse.enableLocalDatastore() must be called first'); } return localDatastore.unPinWithName(_LocalDatastoreUtils.PIN_PREFIX + name); } } const DefaultController = { fetch(target, forceFetch, options) { const localDatastore = _CoreManager.default.getLocalDatastore(); if (Array.isArray(target)) { if (target.length < 1) { return Promise.resolve([]); } const objs = []; const ids = []; let className = null; const results = []; let error = null; target.forEach(el => { if (error) { return; } if (!className) { className = el.className; } if (className !== el.className) { error = new _ParseError.default(_ParseError.default.INVALID_CLASS_NAME, 'All objects should be of the same class'); } if (!el.id) { error = new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'All objects must have an ID'); } if (forceFetch || !el.isDataAvailable()) { ids.push(el.id); objs.push(el); } results.push(el); }); if (error) { return Promise.reject(error); } const ParseQuery = _CoreManager.default.getParseQuery(); const query = new ParseQuery(className); query.containedIn('objectId', ids); if (options && options.include) { query.include(options.include); } query._limit = ids.length; return query.find(options).then(async objects => { const idMap = {}; objects.forEach(o => { idMap[o.id] = o; }); for (let i = 0; i < objs.length; i++) { const obj = objs[i]; if (!obj || !obj.id || !idMap[obj.id]) { if (forceFetch) { return Promise.reject(new _ParseError.default(_ParseError.default.OBJECT_NOT_FOUND, 'All objects must exist on the server.')); } } } if (!singleInstance) { // If single instance objects are disabled, we need to replace the for (let i = 0; i < results.length; i++) { const obj = results[i]; if (obj && obj.id && idMap[obj.id]) { const id = obj.id; obj._finishFetch(idMap[id].toJSON()); results[i] = idMap[id]; } } } for (const object of results) { await localDatastore._updateObjectIfPinned(object); } return Promise.resolve(results); }); } else if (target instanceof ParseObject) { if (!target.id) { return Promise.reject(new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'Object does not have an ID')); } const RESTController = _CoreManager.default.getRESTController(); const params = {}; if (options && options.include) { params.include = options.include.join(); } return RESTController.request('GET', 'classes/' + target.className + '/' + target._getId(), params, options).then(async response => { target._clearPendingOps(); target._clearServerData(); target._finishFetch(response); await localDatastore._updateObjectIfPinned(target); return target; }); } return Promise.resolve(undefined); }, async destroy(target, options) { const batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE'); const localDatastore = _CoreManager.default.getLocalDatastore(); const RESTController = _CoreManager.default.getRESTController(); if (Array.isArray(target)) { if (target.length < 1) { return Promise.resolve([]); } const batches = [[]]; target.forEach(obj => { if (!obj.id) { return; } batches[batches.length - 1].push(obj); if (batches[batches.length - 1].length >= batchSize) { batches.push([]); } }); if (batches[batches.length - 1].length === 0) { // If the last batch is empty, remove it batches.pop(); } let deleteCompleted = Promise.resolve(); const errors = []; batches.forEach(batch => { deleteCompleted = deleteCompleted.then(() => { return RESTController.request('POST', 'batch', { requests: batch.map(obj => { return { method: 'DELETE', path: getServerUrlPath() + 'classes/' + obj.className + '/' + obj._getId(), body: {} }; }) }, options).then(results => { for (let i = 0; i < results.length; i++) { if (results[i] && results[i].hasOwnProperty('error')) { const err = new _ParseError.default(results[i].error.code, results[i].error.error); err.object = batch[i]; errors.push(err); } } }); }); }); return deleteCompleted.then(async () => { if (errors.length) { const aggregate = new _ParseError.default(_ParseError.default.AGGREGATE_ERROR); aggregate.errors = errors; return Promise.reject(aggregate); } for (const object of target) { await localDatastore._destroyObjectIfPinned(object); } return Promise.resolve(target); }); } else if (target instanceof ParseObject) { return RESTController.request('DELETE', 'classes/' + target.className + '/' + target._getId(), {}, options).then(async () => { await localDatastore._destroyObjectIfPinned(target); return Promise.resolve(target); }); } return Promise.resolve(target); }, save(target, options) { const batchSize = options && options.batchSize ? options.batchSize : _CoreManager.default.get('REQUEST_BATCH_SIZE'); const localDatastore = _CoreManager.default.getLocalDatastore(); const mapIdForPin = {}; const RESTController = _CoreManager.default.getRESTController(); const stateController = _CoreManager.default.getObjectStateController(); const allowCustomObjectId = _CoreManager.default.get('ALLOW_CUSTOM_OBJECT_ID'); options = options || {}; options.returnStatus = options.returnStatus || true; if (Array.isArray(target)) { if (target.length < 1) { return Promise.resolve([]); } let unsaved = target.concat(); for (let i = 0; i < target.length; i++) { const target_i = target[i]; if (target_i instanceof ParseObject) { unsaved = unsaved.concat((0, _unsavedChildren.default)(target_i, true)); } } unsaved = (0, _unique.default)(unsaved); const filesSaved = []; let pending = []; unsaved.forEach(el => { if (el instanceof _ParseFile.default) { filesSaved.push(el.save(options)); } else if (el instanceof ParseObject) { pending.push(el); } }); return Promise.all(filesSaved).then(() => { let objectError = null; return (0, _promiseUtils.continueWhile)(() => { return pending.length > 0; }, () => { const batch = []; const nextPending = []; pending.forEach(el => { if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(el, 'id') && !el.id) { throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null'); } if (batch.length < batchSize && (0, _canBeSerialized.default)(el)) { batch.push(el); } else { nextPending.push(el); } }); pending = nextPending; if (batch.length < 1) { return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Tried to save a batch with a cycle.')); } // Queue up tasks for each object in the batch. // When every task is ready, the API request will execute const batchReturned = (0, _promiseUtils.resolvingPromise)(); const batchReady = []; const batchTasks = []; batch.forEach((obj, index) => { const ready = (0, _promiseUtils.resolvingPromise)(); batchReady.push(ready); stateController.pushPendingState(obj._getStateIdentifier()); batchTasks.push(stateController.enqueueTask(obj._getStateIdentifier(), function () { ready.resolve(); return batchReturned.then(responses => { if (responses[index].hasOwnProperty('success')) { const objectId = responses[index].success.objectId; const status = responses[index]._status; delete responses[index]._status; delete responses[index]._headers; delete responses[index]._xhr; mapIdForPin[objectId] = obj._localId; obj._handleSaveResponse(responses[index].success, status); } else { if (!objectError && responses[index].hasOwnProperty('error')) { const serverError = responses[index].error; objectError = new _ParseError.default(serverError.code, serverError.error); // Cancel the rest of the save pending = []; } obj._handleSaveError(); } }); })); }); (0, _promiseUtils.when)(batchReady).then(() => { // Kick off the batch request return RESTController.request('POST', 'batch', { requests: batch.map(obj => { const params = obj._getSaveParams(); params.path = getServerUrlPath() + params.path; return params; }) }, options); }).then(batchReturned.resolve, error => { batchReturned.reject(new _ParseError.default(_ParseError.default.INCORRECT_TYPE, error.message)); }); return (0, _promiseUtils.when)(batchTasks); }).then(async () => { if (objectError) { return Promise.reject(objectError); } for (const object of target) { // Make sure that it is a ParseObject before updating it into the localDataStore if (object instanceof ParseObject) { await localDatastore._updateLocalIdForObject(mapIdForPin[object.id], object); await localDatastore._updateObjectIfPinned(object); } } return Promise.resolve(target); }); }); } else if (target instanceof ParseObject) { if (allowCustomObjectId && Object.prototype.hasOwnProperty.call(target, 'id') && !target.id) { throw new _ParseError.default(_ParseError.default.MISSING_OBJECT_ID, 'objectId must not be empty or null'); } // generate _localId in case if cascadeSave=false target._getId(); const localId = target._localId; // copying target lets guarantee the pointer isn't modified elsewhere const targetCopy = target; const task = function () { const params = targetCopy._getSaveParams(); return RESTController.request(params.method, params.path, params.body, options).then(response => { const status = response._status; delete response._status; delete response._headers; delete response._xhr; targetCopy._handleSaveResponse(response, status); }, error => { targetCopy._handleSaveError(); return Promise.reject(error); }); }; stateController.pushPendingState(target._getStateIdentifier()); return stateController.enqueueTask(target._getStateIdentifier(), task).then(async () => { await localDatastore._updateLocalIdForObject(localId, target); await localDatastore._updateObjectIfPinned(target); return target; }, error => { return Promise.reject(error); }); } return Promise.resolve(undefined); } }; _CoreManager.default.setParseObject(ParseObject); _CoreManager.default.setObjectController(DefaultController); var _default = exports.default = ParseObject;