forked from parse-community/Parse-SDK-JS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParseObject.js
2305 lines (2169 loc) · 72.5 KB
/
ParseObject.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
import CoreManager from './CoreManager';
import canBeSerialized from './canBeSerialized';
import decode from './decode';
import encode from './encode';
import escape from './escape';
import ParseACL from './ParseACL';
import parseDate from './parseDate';
import ParseError from './ParseError';
import ParseFile from './ParseFile';
import { when, continueWhile } from './promiseUtils';
import { DEFAULT_PIN, PIN_PREFIX } from './LocalDatastoreUtils';
import {
opFromJSON,
Op,
SetOp,
UnsetOp,
IncrementOp,
AddOp,
AddUniqueOp,
RemoveOp,
RelationOp
} from './ParseOp';
import ParseQuery from './ParseQuery';
import ParseRelation from './ParseRelation';
import * as SingleInstanceStateController from './SingleInstanceStateController';
import unique from './unique';
import * as UniqueInstanceStateController from './UniqueInstanceStateController';
import unsavedChildren from './unsavedChildren';
import type { AttributeMap, OpsMap } from './ObjectStateMutations';
import type { RequestOptions, FullOptions } from './RESTController';
export type Pointer = {
__type: string;
className: string;
objectId: string;
};
type SaveParams = {
method: string;
path: string;
body: AttributeMap;
};
type SaveOptions = FullOptions & {
cascadeSave?: boolean
}
const DEFAULT_BATCH_SIZE = 20;
// 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 local Ids
let localCount = 0;
// 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.get('IS_NODE'));
if (singleInstance) {
CoreManager.setObjectStateController(SingleInstanceStateController);
} else {
CoreManager.setObjectStateController(UniqueInstanceStateController);
}
function getServerUrlPath() {
let serverUrl = CoreManager.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.
*
* <p>You won't normally call this method directly. It is recommended that
* you use a subclass of <code>Parse.Object</code> instead, created by calling
* <code>extend</code>.</p>
*
* <p>However, if you don't want to use a subclass, or aren't sure which
* subclass is appropriate, you can use this form:<pre>
* var object = new Parse.Object("ClassName");
* </pre>
* That is basically equivalent to:<pre>
* var MyClass = Parse.Object.extend("ClassName");
* var object = new MyClass();
* </pre></p>
*
* @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.
*/
constructor(className: ?string | { className: string, [attr: string]: mixed }, attributes?: { [attr: string]: mixed }, options?: { ignoreValidation: boolean }) {
// 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 id
* @type String
*/
id: ?string;
_localId: ?string;
_objCount: number;
className: string;
/** Prototype getters / setters **/
get attributes(): AttributeMap {
const stateController = CoreManager.getObjectStateController();
return Object.freeze(stateController.estimateAttributes(this._getStateIdentifier()));
}
/**
* The first time this object was saved on the server.
* @property createdAt
* @type Date
*/
get createdAt(): ?Date {
return this._getServerData().createdAt;
}
/**
* The last time this object was updated on the server.
* @property updatedAt
* @type Date
*/
get updatedAt(): ?Date {
return this._getServerData().updatedAt;
}
/** Private methods **/
/**
* Returns a local or server Id used uniquely identify this object
*/
_getId(): string {
if (typeof this.id === 'string') {
return this.id;
}
if (typeof this._localId === 'string') {
return this._localId;
}
const localId = 'local' + String(localCount++);
this._localId = localId;
return localId;
}
/**
* Returns a unique identifier used to pull data from the State Controller.
*/
_getStateIdentifier(): ParseObject | {id: string, className: string} {
if (singleInstance) {
let id = this.id;
if (!id) {
id = this._getId();
}
return {
id: id,
className: this.className
};
} else {
return this;
}
}
_getServerData(): AttributeMap {
const stateController = CoreManager.getObjectStateController();
return stateController.getServerData(this._getStateIdentifier());
}
_clearServerData() {
const serverData = this._getServerData();
const unset = {};
for (const attr in serverData) {
unset[attr] = undefined;
}
const stateController = CoreManager.getObjectStateController();
stateController.setServerData(this._getStateIdentifier(), unset);
}
_getPendingOps(): Array<OpsMap> {
const stateController = CoreManager.getObjectStateController();
return stateController.getPendingOps(this._getStateIdentifier());
}
/**
* @param {Array<string>} [keysToClear] - if specified, only ops matching
* these fields will be cleared
*/
_clearPendingOps(keysToClear?: Array<string>) {
const pending = this._getPendingOps();
const latest = pending[pending.length - 1];
const keys = keysToClear || Object.keys(latest);
keys.forEach((key) => {
delete latest[key];
});
}
_getDirtyObjectAttributes(): AttributeMap {
const attributes = this.attributes;
const stateController = CoreManager.getObjectStateController();
const objectCache = stateController.getObjectCache(this._getStateIdentifier());
const dirty = {};
for (const attr in attributes) {
const val = attributes[attr];
if (val &&
typeof val === 'object' &&
!(val instanceof ParseObject) &&
!(val instanceof ParseFile) &&
!(val instanceof ParseRelation)
) {
// Due to the way browsers construct maps, the key order will not change
// unless the object is changed
try {
const json = encode(val, false, true);
const stringified = JSON.stringify(json);
if (objectCache[attr] !== stringified) {
dirty[attr] = val;
}
} catch (e) {
// Error occurred, possibly by a nested unsaved pointer in a mutable container
// No matter how it happened, it indicates a change in the attribute
dirty[attr] = val;
}
}
}
return dirty;
}
_toFullJSON(seen?: Array<any>): AttributeMap {
const json: { [key: string]: mixed } = this.toJSON(seen);
json.__type = 'Object';
json.className = this.className;
return json;
}
_getSaveJSON(): AttributeMap {
const pending = this._getPendingOps();
const dirtyObjects = this._getDirtyObjectAttributes();
const json = {};
let attr;
for (attr in dirtyObjects) {
let isDotNotation = false;
for (let i = 0; i < pending.length; i += 1) {
for (const field in pending[i]) {
// Dot notation operations are handled later
if (field.includes('.')) {
const fieldName = field.split('.')[0];
if (fieldName === attr) {
isDotNotation = true;
break;
}
}
}
}
if (!isDotNotation) {
json[attr] = new SetOp(dirtyObjects[attr]).toJSON();
}
}
for (attr in pending[0]) {
json[attr] = pending[0][attr].toJSON();
}
return json;
}
_getSaveParams(): SaveParams {
const method = this.id ? 'PUT' : 'POST';
const body = this._getSaveJSON();
let path = 'classes/' + this.className;
if (this.id) {
path += '/' + this.id;
} else if (this.className === '_User') {
path = 'users';
}
return {
method,
body,
path
};
}
_finishFetch(serverData: AttributeMap) {
if (!this.id && serverData.objectId) {
this.id = serverData.objectId;
}
const stateController = CoreManager.getObjectStateController();
stateController.initializeState(this._getStateIdentifier());
const decoded = {};
for (const attr in serverData) {
if (attr === 'ACL') {
decoded[attr] = new ParseACL(serverData[attr]);
} else if (attr !== 'objectId') {
decoded[attr] = decode(serverData[attr]);
if (decoded[attr] instanceof ParseRelation) {
decoded[attr]._ensureParentAndKey(this, attr);
}
}
}
if (decoded.createdAt && typeof decoded.createdAt === 'string') {
decoded.createdAt = parseDate(decoded.createdAt);
}
if (decoded.updatedAt && typeof decoded.updatedAt === 'string') {
decoded.updatedAt = parseDate(decoded.updatedAt);
}
if (!decoded.updatedAt && decoded.createdAt) {
decoded.updatedAt = decoded.createdAt;
}
stateController.commitServerChanges(this._getStateIdentifier(), decoded);
}
_setExisted(existed: boolean) {
const stateController = CoreManager.getObjectStateController();
const state = stateController.getState(this._getStateIdentifier());
if (state) {
state.existed = existed;
}
}
_migrateId(serverId: string) {
if (this._localId && serverId) {
if (singleInstance) {
const stateController = CoreManager.getObjectStateController();
const oldState = stateController.removeState(this._getStateIdentifier());
this.id = serverId;
delete this._localId;
if (oldState) {
stateController.initializeState(this._getStateIdentifier(), oldState);
}
} else {
this.id = serverId;
delete this._localId;
}
}
}
_handleSaveResponse(response: AttributeMap, status: number) {
const changes = {};
let attr;
const stateController = CoreManager.getObjectStateController();
const pending = stateController.popPendingState(this._getStateIdentifier());
for (attr in pending) {
if (pending[attr] instanceof RelationOp) {
changes[attr] = pending[attr].applyTo(undefined, this, attr);
} else if (!(attr in response)) {
// Only SetOps and UnsetOps should not come back with results
changes[attr] = pending[attr].applyTo(undefined);
}
}
for (attr in response) {
if ((attr === 'createdAt' || attr === 'updatedAt') &&
typeof response[attr] === 'string') {
changes[attr] = parseDate(response[attr]);
} else if (attr === 'ACL') {
changes[attr] = new ParseACL(response[attr]);
} else if (attr !== 'objectId') {
changes[attr] = decode(response[attr]);
if (changes[attr] instanceof UnsetOp) {
changes[attr] = undefined;
}
}
}
if (changes.createdAt && !changes.updatedAt) {
changes.updatedAt = changes.createdAt;
}
this._migrateId(response.objectId);
if (status !== 201) {
this._setExisted(true);
}
stateController.commitServerChanges(this._getStateIdentifier(), changes);
}
_handleSaveError() {
const stateController = CoreManager.getObjectStateController();
stateController.mergeFirstPendingState(this._getStateIdentifier());
}
/** Public methods **/
initialize() {
// NOOP
}
/**
* Returns a JSON version of the object suitable for saving to Parse.
* @return {Object}
*/
toJSON(seen: Array<any> | void): AttributeMap {
const seenEntry = this.id ? this.className + ':' + this.id : this;
seen = seen || [seenEntry];
const json = {};
const attrs = this.attributes;
for (const attr in attrs) {
if ((attr === 'createdAt' || attr === 'updatedAt') && attrs[attr].toJSON) {
json[attr] = attrs[attr].toJSON();
} else {
json[attr] = encode(attrs[attr], false, false, seen);
}
}
const pending = this._getPendingOps();
for (const attr in pending[0]) {
json[attr] = pending[0][attr].toJSON();
}
if (this.id) {
json.objectId = this.id;
}
return json;
}
/**
* Determines whether this ParseObject is equal to another ParseObject
* @param {Object} other - An other object ot compare
* @return {Boolean}
*/
equals(other: mixed): boolean {
if (this === other) {
return true;
}
return (
(other instanceof ParseObject) &&
this.className === other.className &&
this.id === other.id &&
typeof this.id !== 'undefined'
);
}
/**
* Returns true if this object has been modified since its last
* save/refresh. If an attribute is specified, it returns true only if that
* particular attribute has been modified since the last save/refresh.
* @param {String} attr An attribute name (optional).
* @return {Boolean}
*/
dirty(attr?: string): boolean {
if (!this.id) {
return true;
}
const pendingOps = this._getPendingOps();
const dirtyObjects = this._getDirtyObjectAttributes();
if (attr) {
if (dirtyObjects.hasOwnProperty(attr)) {
return true;
}
for (let i = 0; i < pendingOps.length; i++) {
if (pendingOps[i].hasOwnProperty(attr)) {
return true;
}
}
return false;
}
if (Object.keys(pendingOps[0]).length !== 0) {
return true;
}
if (Object.keys(dirtyObjects).length !== 0) {
return true;
}
return false;
}
/**
* Returns an array of keys that have been modified since last save/refresh
* @return {String[]}
*/
dirtyKeys(): Array<string> {
const pendingOps = this._getPendingOps();
const keys = {};
for (let i = 0; i < pendingOps.length; i++) {
for (const attr in pendingOps[i]) {
keys[attr] = true;
}
}
const dirtyObjects = this._getDirtyObjectAttributes();
for (const attr in dirtyObjects) {
keys[attr] = true;
}
return Object.keys(keys);
}
/**
* Returns true if the object has been fetched.
* @return {Boolean}
*/
isDataAvailable(): boolean {
const serverData = this._getServerData();
return !!Object.keys(serverData).length;
}
/**
* Gets a Pointer referencing this Object.
* @return {Pointer}
*/
toPointer(): Pointer {
if (!this.id) {
throw new Error('Cannot create a pointer to an unsaved ParseObject');
}
return {
__type: 'Pointer',
className: this.className,
objectId: this.id
};
}
/**
* Gets the value of an attribute.
* @param {String} attr The string name of an attribute.
*/
get(attr: string): mixed {
return this.attributes[attr];
}
/**
* Gets a relation on the given class for the attribute.
* @param String attr The attribute to get the relation for.
* @return {Parse.Relation}
*/
relation(attr: string): ParseRelation {
const value = this.get(attr);
if (value) {
if (!(value instanceof ParseRelation)) {
throw new Error('Called relation() on non-relation field ' + attr);
}
value._ensureParentAndKey(this, attr);
return value;
}
return new ParseRelation(this, attr);
}
/**
* Gets the HTML-escaped value of an attribute.
* @param {String} attr The string name of an attribute.
*/
escape(attr: string): string {
let val = this.attributes[attr];
if (val == null) {
return '';
}
if (typeof val !== 'string') {
if (typeof val.toString !== 'function') {
return '';
}
val = val.toString();
}
return escape(val);
}
/**
* Returns <code>true</code> if the attribute contains a value that is not
* null or undefined.
* @param {String} attr The string name of the attribute.
* @return {Boolean}
*/
has(attr: string): boolean {
const attributes = this.attributes;
if (attributes.hasOwnProperty(attr)) {
return attributes[attr] != null;
}
return false;
}
/**
* Sets a hash of model attributes on the object.
*
* <p>You can call it with an object containing keys and values, with one
* key and value, or dot notation. For example:<pre>
* 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);</pre></p>
*
* game.set("player.score", 10);</pre></p>
*
* @param {String} key The key to set.
* @param {} value The value to give it.
* @param {Object} options A set of options for the set.
* The only supported option is <code>error</code>.
* @return {(ParseObject|Boolean)} true if the set succeeded.
*/
set(key: mixed, value: mixed, options?: mixed): ParseObject | boolean {
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 UnsetOp();
} else if (changes[k] instanceof Op) {
newOps[k] = changes[k];
} else if (changes[k] &&
typeof changes[k] === 'object' &&
typeof changes[k].__op === 'string'
) {
newOps[k] = 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)
) {
newOps[k] = new SetOp(new ParseACL(changes[k]));
} else if (changes[k] instanceof ParseRelation) {
const relation = new ParseRelation(this, k);
relation.targetClassName = changes[k].targetClassName;
newOps[k] = new SetOp(relation);
} else {
newOps[k] = new SetOp(changes[k]);
}
}
const currentAttributes = this.attributes;
// Only set nested fields if exists
const serverData = this._getServerData();
if (typeof key === 'string' && key.includes('.')) {
const field = key.split('.')[0];
if (!serverData[field]) {
return this;
}
}
// Calculate new values
const newValues = {};
for (const attr in newOps) {
if (newOps[attr] instanceof RelationOp) {
newValues[attr] = newOps[attr].applyTo(currentAttributes[attr], this, attr);
} else if (!(newOps[attr] instanceof 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.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.
* @return {(ParseObject|Boolean)}
*/
unset(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).
* @return {(ParseObject|Boolean)}
*/
increment(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 IncrementOp(amount));
}
/**
* 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.
* @return {(ParseObject|Boolean)}
*/
add(attr: string, item: mixed): ParseObject | boolean {
return this.set(attr, new 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.
* @return {(ParseObject|Boolean)}
*/
addAll(attr: string, items: Array<mixed>): ParseObject | boolean {
return this.set(attr, new 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.
* @return {(ParseObject|Boolean)}
*/
addUnique(attr: string, item: mixed): ParseObject | boolean {
return this.set(attr, new 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.
* @return {(ParseObject|Boolean)}
*/
addAllUnique(attr: string, items: Array<mixed>): ParseObject | boolean {
return this.set(attr, new 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.
* @return {(ParseObject|Boolean)}
*/
remove(attr: string, item: mixed): ParseObject | boolean {
return this.set(attr, new 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.
* @return {(ParseObject|Boolean)}
*/
removeAll(attr: string, items: Array<mixed>): ParseObject | boolean {
return this.set(attr, new 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} The operation, or undefined if none.
*/
op(attr: string): ?Op {
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.
* @return {Parse.Object}
*/
clone(): any {
const clone = new this.constructor();
if (!clone.className) {
clone.className = 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()
* @return {Parse.Object}
*/
newInstance(): any {
const clone = new this.constructor();
if (!clone.className) {
clone.className = this.className;
}
clone.id = this.id;
if (singleInstance) {
// Just return an object with the right id
return clone;
}
const stateController = CoreManager.getObjectStateController();
if (stateController) {
stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier());
}
return clone;
}
/**
* Returns true if this object has never been saved to Parse.
* @return {Boolean}
*/
isNew(): boolean {
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)
* @return {Boolean}
*/
existed(): boolean {
if (!this.id) {
return false;
}
const stateController = CoreManager.getObjectStateController();
const state = stateController.getState(this._getStateIdentifier());
if (state) {
return state.existed;
}
return false;
}
/**
* Checks if the model is currently in a valid state.
* @return {Boolean}
*/
isValid(): boolean {
return !this.validate(this.attributes);
}
/**
* You should not call this function directly unless you subclass
* <code>Parse.Object</code>, in which case you can override this method
* to provide additional validation on <code>set</code> and
* <code>save</code>. Your implementation should return
*
* @param {Object} attrs The current data to validate.
* @return {} False if the data is valid. An error object otherwise.
* @see Parse.Object#set
*/
validate(attrs: AttributeMap): ParseError | boolean {
if (attrs.hasOwnProperty('ACL') && !(attrs.ACL instanceof ParseACL)) {
return new ParseError(
ParseError.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(ParseError.INVALID_KEY_NAME);
}
}
return false;
}
/**
* Returns the ACL for this object.
* @returns {Parse.ACL} An instance of Parse.ACL.
* @see Parse.Object#get
*/
getACL(): ?ParseACL {
const acl = this.get('ACL');
if (acl instanceof ParseACL) {
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
* @return {(ParseObject|Boolean)} Whether the set passed validation.
* @see Parse.Object#set
*/
setACL(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
*/
revert(...keys: Array<string>): void {
let keysToRevert;
if(keys.length) {
keysToRevert = [];