forked from leancloud/javascript-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject.js
More file actions
1600 lines (1452 loc) · 49.9 KB
/
Copy pathobject.js
File metadata and controls
1600 lines (1452 loc) · 49.9 KB
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
/**
* 每位工程师都有保持代码优雅的义务
* Each engineer has a duty to keep the code elegant
**/
const _ = require('underscore');
const AVError = require('./error');
const AVRequest = require('./request').request;
const utils = require('./utils');
// AV.Object is analogous to the Java AVObject.
// It also implements the same interface as a Backbone model.
module.exports = function(AV) {
/**
* Creates a new model with defined attributes. A client id (cid) is
* automatically generated and assigned for you.
*
* <p>You won't normally call this method directly. It is recommended that
* you use a subclass of <code>AV.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 AV.Object("ClassName");
* </pre>
* That is basically equivalent to:<pre>
* var MyClass = AV.Object.extend("ClassName");
* var object = new MyClass();
* </pre></p>
*
* @param {Object} attributes The initial set of data to store in the object.
* @param {Object} options A set of Backbone-like options for creating the
* object. The only option currently supported is "collection".
* @see AV.Object.extend
*
* @class
*
* <p>The fundamental unit of AV data, which implements the Backbone Model
* interface.</p>
*/
AV.Object = function(attributes, options) {
// Allow new AV.Object("ClassName") as a shortcut to _create.
if (_.isString(attributes)) {
return AV.Object._create.apply(this, arguments);
}
attributes = attributes || {};
if (options && options.parse) {
attributes = this.parse(attributes);
}
var defaults = AV._getValue(this, 'defaults');
if (defaults) {
attributes = _.extend({}, defaults, attributes);
}
if (options && options.collection) {
this.collection = options.collection;
}
this._serverData = {}; // The last known data for this object from cloud.
this._opSetQueue = [{}]; // List of sets of changes to the data.
this.attributes = {}; // The best estimate of this's current data.
this._hashedJSON = {}; // Hash of values of containers at last save.
this._escapedAttributes = {};
this.cid = _.uniqueId('c');
this.changed = {};
this._silent = {};
this._pending = {};
if (!this.set(attributes, {silent: true})) {
throw new Error("Can't create an invalid AV.Object");
}
this.changed = {};
this._silent = {};
this._pending = {};
this._hasData = true;
this._previousAttributes = _.clone(this.attributes);
this.initialize.apply(this, arguments);
};
/**
* @lends AV.Object.prototype
* @property {String} id The objectId of the AV Object.
*/
/**
* Saves the given list of AV.Object.
* If any error is encountered, stops and calls the error handler.
* There are two ways you can call this function.
*
* The Backbone way:<pre>
* AV.Object.saveAll([object1, object2, ...], {
* success: function(list) {
* // All the objects were saved.
* },
* error: function(error) {
* // An error occurred while saving one of the objects.
* },
* });
* </pre>
* A simplified syntax:<pre>
* AV.Object.saveAll([object1, object2, ...], function(list, error) {
* if (list) {
* // All the objects were saved.
* } else {
* // An error occurred.
* }
* });
* </pre>
*
* @param {Array} list A list of <code>AV.Object</code>.
* @param {Object} options A Backbone-style callback object.
*/
AV.Object.saveAll = function(list, options) {
return AV.Object._deepSaveAsync(list, null, options)._thenRunCallbacks(options);
};
/**
* Fetch the given list of AV.Object.
*
* @param {AV.Object[]} objects A list of <code>AV.Object</code>
* @param {Object} options
* @param {String} options.sessionToken specify user's session, used in LeanEngine.
* @return {Promise.<AV.Object[]>} The given list of <code>AV.Object</code>, updated
*/
AV.Object.fetchAll = (objects, options) =>
AV.Promise.as().then(() =>
AVRequest('batch', null, null, 'POST', {
requests: _.map(objects, object => {
if (!object.className) throw new Error('object must have className to fetch');
if (!object.id) throw new Error('object must have id to fetch');
if (object.dirty()) throw new Error('object is modified but not saved');
return {
method: 'GET',
path: `/1.1/classes/${object.className}/${object.id}`,
};
}),
}, options && options.sessionToken)
).then(function(response) {
_.forEach(objects, function(object, i) {
if (response[i].success) {
object._finishFetch(
object.parse(response[i].success));
} else {
const error = new Error(response[i].error.error);
error.code = response[i].error.code;
throw error;
}
});
return objects;
});
// Attach all inheritable methods to the AV.Object prototype.
_.extend(AV.Object.prototype, AV.Events,
/** @lends AV.Object.prototype */ {
_fetchWhenSave: false,
/**
* Initialize is an empty function by default. Override it with your own
* initialization logic.
*/
initialize: function(){},
/**
* Set whether to enable fetchWhenSave option when updating object.
* When set true, SDK would fetch the latest object after saving.
* Default is false.
*
* @deprecated use AV.Object#save with options.fetchWhenSave instead
* @param {boolean} enable true to enable fetchWhenSave option.
*/
fetchWhenSave: function(enable){
console.warn('AV.Object#fetchWhenSave is deprecated, use AV.Object#save with options.fetchWhenSave instead.');
if (!_.isBoolean(enable)) {
throw "Expect boolean value for fetchWhenSave";
}
this._fetchWhenSave = enable;
},
/**
* Returns the object's objectId.
* @return {String} the objectId.
*/
getObjectId: function() {
return this.id;
},
/**
* Returns the object's createdAt attribute.
* @return {Date}
*/
getCreatedAt: function() {
return this.createdAt || this.get('createdAt');
},
/**
* Returns the object's updatedAt attribute.
* @return {Date}
*/
getUpdatedAt: function() {
return this.updatedAt || this.get('updatedAt');
},
/**
* Returns a JSON version of the object suitable for saving to AV.
* @return {Object}
*/
toJSON: function() {
var json = this._toFullJSON();
AV._arrayEach(["__type", "className"],
function(key) { delete json[key]; });
return json;
},
_toFullJSON: function(seenObjects) {
var json = _.clone(this.attributes);
AV._objectEach(json, function(val, key) {
json[key] = AV._encode(val, seenObjects);
});
AV._objectEach(this._operations, function(val, key) {
json[key] = val;
});
if (_.has(this, "id")) {
json.objectId = this.id;
}
if (_.has(this, "createdAt")) {
if (_.isDate(this.createdAt)) {
json.createdAt = this.createdAt.toJSON();
} else {
json.createdAt = this.createdAt;
}
}
if (_.has(this, "updatedAt")) {
if (_.isDate(this.updatedAt)) {
json.updatedAt = this.updatedAt.toJSON();
} else {
json.updatedAt = this.updatedAt;
}
}
json.__type = "Object";
json.className = this.className;
return json;
},
/**
* Updates _hashedJSON to reflect the current state of this object.
* Adds any changed hash values to the set of pending changes.
*/
_refreshCache: function() {
var self = this;
if (self._refreshingCache) {
return;
}
self._refreshingCache = true;
AV._objectEach(this.attributes, function(value, key) {
if (value instanceof AV.Object) {
value._refreshCache();
} else if (_.isObject(value)) {
if (self._resetCacheForKey(key)) {
self.set(key, new AV.Op.Set(value), { silent: true });
}
}
});
delete self._refreshingCache;
},
/**
* 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: function(attr) {
this._refreshCache();
var currentChanges = _.last(this._opSetQueue);
if (attr) {
return (currentChanges[attr] ? true : false);
}
if (!this.id) {
return true;
}
if (_.keys(currentChanges).length > 0) {
return true;
}
return false;
},
/**
* Gets a Pointer referencing this Object.
*/
_toPointer: function() {
// if (!this.id) {
// throw new Error("Can't serialize an unsaved AV.Object");
// }
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: function(attr) {
switch (attr) {
case 'objectId':
case 'id':
return this.id;
case 'createdAt':
case 'updatedAt':
return this[attr];
default:
return this.attributes[attr];
}
},
/**
* Gets a relation on the given class for the attribute.
* @param String attr The attribute to get the relation for.
*/
relation: function(attr) {
var value = this.get(attr);
if (value) {
if (!(value instanceof AV.Relation)) {
throw "Called relation() on non-relation field " + attr;
}
value._ensureParentAndKey(this, attr);
return value;
} else {
return new AV.Relation(this, attr);
}
},
/**
* Gets the HTML-escaped value of an attribute.
*/
escape: function(attr) {
var html = this._escapedAttributes[attr];
if (html) {
return html;
}
var val = this.attributes[attr];
var escaped;
if (utils.isNullOrUndefined(val)) {
escaped = '';
} else {
escaped = _.escape(val.toString());
}
this._escapedAttributes[attr] = escaped;
return escaped;
},
/**
* 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: function(attr) {
return !utils.isNullOrUndefined(this.attributes[attr]);
},
/**
* Pulls "special" fields like objectId, createdAt, etc. out of attrs
* and puts them on "this" directly. Removes them from attrs.
* @param attrs - A dictionary with the data for this AV.Object.
*/
_mergeMagicFields: function(attrs) {
// Check for changes of magic fields.
var model = this;
var specialFields = ["id", "objectId", "createdAt", "updatedAt"];
AV._arrayEach(specialFields, function(attr) {
if (attrs[attr]) {
if (attr === "objectId") {
model.id = attrs[attr];
} else if ((attr === "createdAt" || attr === "updatedAt") &&
!_.isDate(attrs[attr])) {
model[attr] = AV._parseDate(attrs[attr]);
} else {
model[attr] = attrs[attr];
}
delete attrs[attr];
}
});
},
/**
* Returns the json to be sent to the server.
*/
_startSave: function() {
this._opSetQueue.push({});
},
/**
* Called when a save fails because of an error. Any changes that were part
* of the save need to be merged with changes made after the save. This
* might throw an exception is you do conflicting operations. For example,
* if you do:
* object.set("foo", "bar");
* object.set("invalid field name", "baz");
* object.save();
* object.increment("foo");
* then this will throw when the save fails and the client tries to merge
* "bar" with the +1.
*/
_cancelSave: function() {
var self = this;
var failedChanges = _.first(this._opSetQueue);
this._opSetQueue = _.rest(this._opSetQueue);
var nextChanges = _.first(this._opSetQueue);
AV._objectEach(failedChanges, function(op, key) {
var op1 = failedChanges[key];
var op2 = nextChanges[key];
if (op1 && op2) {
nextChanges[key] = op2._mergeWithPrevious(op1);
} else if (op1) {
nextChanges[key] = op1;
}
});
this._saving = this._saving - 1;
},
/**
* Called when a save completes successfully. This merges the changes that
* were saved into the known server data, and overrides it with any data
* sent directly from the server.
*/
_finishSave: function(serverData) {
// Grab a copy of any object referenced by this object. These instances
// may have already been fetched, and we don't want to lose their data.
// Note that doing it like this means we will unify separate copies of the
// same object, but that's a risk we have to take.
var fetchedObjects = {};
AV._traverse(this.attributes, function(object) {
if (object instanceof AV.Object && object.id && object._hasData) {
fetchedObjects[object.id] = object;
}
});
var savedChanges = _.first(this._opSetQueue);
this._opSetQueue = _.rest(this._opSetQueue);
this._applyOpSet(savedChanges, this._serverData);
this._mergeMagicFields(serverData);
var self = this;
AV._objectEach(serverData, function(value, key) {
self._serverData[key] = AV._decode(key, value);
// Look for any objects that might have become unfetched and fix them
// by replacing their values with the previously observed values.
var fetched = AV._traverse(self._serverData[key], function(object) {
if (object instanceof AV.Object && fetchedObjects[object.id]) {
return fetchedObjects[object.id];
}
});
if (fetched) {
self._serverData[key] = fetched;
}
});
this._rebuildAllEstimatedData();
this._saving = this._saving - 1;
},
/**
* Called when a fetch or login is complete to set the known server data to
* the given object.
*/
_finishFetch: function(serverData, hasData) {
// Clear out any changes the user might have made previously.
this._opSetQueue = [{}];
// Bring in all the new server data.
this._mergeMagicFields(serverData);
var self = this;
AV._objectEach(serverData, function(value, key) {
self._serverData[key] = AV._decode(key, value);
});
// Refresh the attributes.
this._rebuildAllEstimatedData();
// Clear out the cache of mutable containers.
this._refreshCache();
this._opSetQueue = [{}];
this._hasData = hasData;
},
/**
* Applies the set of AV.Op in opSet to the object target.
*/
_applyOpSet: function(opSet, target) {
var self = this;
AV._objectEach(opSet, function(change, key) {
target[key] = change._estimate(target[key], self, key);
if (target[key] === AV.Op._UNSET) {
delete target[key];
}
});
},
/**
* Replaces the cached value for key with the current value.
* Returns true if the new value is different than the old value.
*/
_resetCacheForKey: function(key) {
var value = this.attributes[key];
if (_.isObject(value) &&
!(value instanceof AV.Object) &&
!(value instanceof AV.File)) {
value = value.toJSON ? value.toJSON() : value;
var json = JSON.stringify(value);
if (this._hashedJSON[key] !== json) {
var wasSet = !! this._hashedJSON[key];
this._hashedJSON[key] = json;
return wasSet;
}
}
return false;
},
/**
* Populates attributes[key] by starting with the last known data from the
* server, and applying all of the local changes that have been made to that
* key since then.
*/
_rebuildEstimatedDataForKey: function(key) {
var self = this;
delete this.attributes[key];
if (this._serverData[key]) {
this.attributes[key] = this._serverData[key];
}
AV._arrayEach(this._opSetQueue, function(opSet) {
var op = opSet[key];
if (op) {
self.attributes[key] = op._estimate(self.attributes[key], self, key);
if (self.attributes[key] === AV.Op._UNSET) {
delete self.attributes[key];
} else {
self._resetCacheForKey(key);
}
}
});
},
/**
* Populates attributes by starting with the last known data from the
* server, and applying all of the local changes that have been made since
* then.
*/
_rebuildAllEstimatedData: function() {
var self = this;
var previousAttributes = _.clone(this.attributes);
this.attributes = _.clone(this._serverData);
AV._arrayEach(this._opSetQueue, function(opSet) {
self._applyOpSet(opSet, self.attributes);
AV._objectEach(opSet, function(op, key) {
self._resetCacheForKey(key);
});
});
// Trigger change events for anything that changed because of the fetch.
AV._objectEach(previousAttributes, function(oldValue, key) {
if (self.attributes[key] !== oldValue) {
self.trigger('change:' + key, self, self.attributes[key], {});
}
});
AV._objectEach(this.attributes, function(newValue, key) {
if (!_.has(previousAttributes, key)) {
self.trigger('change:' + key, self, newValue, {});
}
});
},
/**
* Sets a hash of model attributes on the object, firing
* <code>"change"</code> unless you choose to silence it.
*
* <p>You can call it with an object containing keys and values, or with one
* key and value. 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>
*
* @param {String} key The key to set.
* @param {} value The value to give it.
* @param {Object} options A set of Backbone-like options for the set.
* The only supported options are <code>silent</code>,
* <code>error</code>, and <code>promise</code>.
* @return {AV.Object} self if succeeded, false if the value is not valid.
* @see AV.Object#validate
* @see AVError
*/
set: function(key, value, options) {
var attrs, attr;
if (_.isObject(key) || utils.isNullOrUndefined(key)) {
attrs = key;
AV._objectEach(attrs, function(v, k) {
attrs[k] = AV._decode(k, v);
});
options = value;
} else {
attrs = {};
attrs[key] = AV._decode(key, value);
}
// Extract attributes and options.
options = options || {};
if (!attrs) {
return this;
}
if (attrs instanceof AV.Object) {
attrs = attrs.attributes;
}
// If the unset option is used, every attribute should be a Unset.
if (options.unset) {
AV._objectEach(attrs, function(unused_value, key) {
attrs[key] = new AV.Op.Unset();
});
}
// Apply all the attributes to get the estimated values.
var dataToValidate = _.clone(attrs);
var self = this;
AV._objectEach(dataToValidate, function(value, key) {
if (value instanceof AV.Op) {
dataToValidate[key] = value._estimate(self.attributes[key],
self, key);
if (dataToValidate[key] === AV.Op._UNSET) {
delete dataToValidate[key];
}
}
});
// Run validation.
if (!this._validate(attrs, options)) {
return false;
}
this._mergeMagicFields(attrs);
options.changes = {};
var escaped = this._escapedAttributes;
var prev = this._previousAttributes || {};
// Update attributes.
AV._arrayEach(_.keys(attrs), function(attr) {
var val = attrs[attr];
// If this is a relation object we need to set the parent correctly,
// since the location where it was parsed does not have access to
// this object.
if (val instanceof AV.Relation) {
val.parent = self;
}
if (!(val instanceof AV.Op)) {
val = new AV.Op.Set(val);
}
// See if this change will actually have any effect.
var isRealChange = true;
if (val instanceof AV.Op.Set &&
_.isEqual(self.attributes[attr], val.value)) {
isRealChange = false;
}
if (isRealChange) {
delete escaped[attr];
if (options.silent) {
self._silent[attr] = true;
} else {
options.changes[attr] = true;
}
}
var currentChanges = _.last(self._opSetQueue);
currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]);
self._rebuildEstimatedDataForKey(attr);
if (isRealChange) {
self.changed[attr] = self.attributes[attr];
if (!options.silent) {
self._pending[attr] = true;
}
} else {
delete self.changed[attr];
delete self._pending[attr];
}
});
if (!options.silent) {
this.change(options);
}
return this;
},
/**
* Remove an attribute from the model, firing <code>"change"</code> unless
* you choose to silence it. This is a noop if the attribute doesn't
* exist.
*/
unset: function(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.
*/
increment: function(attr, amount) {
if (_.isUndefined(amount) || _.isNull(amount)) {
amount = 1;
}
return this.set(attr, new AV.Op.Increment(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.
*/
add: function(attr, item) {
return this.set(attr, new AV.Op.Add(utils.ensureArray(item)));
},
/**
* 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.
*/
addUnique: function(attr, item) {
return this.set(attr, new AV.Op.AddUnique(utils.ensureArray(item)));
},
/**
* 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.
*/
remove: function(attr, item) {
return this.set(attr, new AV.Op.Remove(utils.ensureArray(item)));
},
/**
* Returns an instance of a subclass of AV.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 AV.Op.Increment.
*
* @param attr {String} The key.
* @returns {AV.Op} The operation, or undefined if none.
*/
op: function(attr) {
return _.last(this._opSetQueue)[attr];
},
/**
* Clear all attributes on the model, firing <code>"change"</code> unless
* you choose to silence it.
*/
clear: function(options) {
options = options || {};
options.unset = true;
var keysToClear = _.extend(this.attributes, this._operations);
return this.set(keysToClear, options);
},
/**
* Returns a JSON-encoded set of operations to be sent with the next save
* request.
*/
_getSaveJSON: function() {
var json = _.clone(_.first(this._opSetQueue));
AV._objectEach(json, function(op, key) {
json[key] = op.toJSON();
});
return json;
},
/**
* Returns true if this object can be serialized for saving.
*/
_canBeSerialized: function() {
return AV.Object._canBeSerializedAsValue(this.attributes);
},
/**
* Fetch the model from the server. If the server's representation of the
* model differs from its current attributes, they will be overriden,
* triggering a <code>"change"</code> event.
* @param {Object} fetchOptions Optional options to set 'keys' and
* 'include' option.
* @param {Object} options Optional Backbone-like options object to be
* passed in to set.
* @return {AV.Promise} A promise that is fulfilled when the fetch
* completes.
*/
fetch: function() {
var options = {};
var fetchOptions = {};
if(arguments.length === 1) {
options = arguments[0];
} else if(arguments.length === 2) {
fetchOptions = arguments[0];
options = arguments[1] || {};
}
if (fetchOptions && fetchOptions.include && _.isArray(fetchOptions.include)) {
fetchOptions.include = fetchOptions.include.join(',');
}
var self = this;
var request = AVRequest('classes', this.className, this.id, 'GET',
fetchOptions, options.sessionToken);
return request.then(function(response) {
self._finishFetch(self.parse(response), true);
return self;
})._thenRunCallbacks(options, this);
},
/**
* Set a hash of model attributes, and save the model to the server.
* updatedAt will be updated when the request returns.
* You can either call it as:<pre>
* object.save();</pre>
* or<pre>
* object.save(null, options);</pre>
* or<pre>
* object.save(attrs, options);</pre>
* or<pre>
* object.save(key, value, options);</pre>
*
* For example, <pre>
* gameTurn.save({
* player: "Jake Cutter",
* diceRoll: 2
* }, {
* success: function(gameTurnAgain) {
* // The save was successful.
* },
* error: function(gameTurnAgain, error) {
* // The save failed. Error is an instance of AVError.
* }
* });</pre>
* or with promises:<pre>
* gameTurn.save({
* player: "Jake Cutter",
* diceRoll: 2
* }).then(function(gameTurnAgain) {
* // The save was successful.
* }, function(error) {
* // The save failed. Error is an instance of AVError.
* });</pre>
* @param {Object} options Optional Backbone-like options object to be passed in to set.
* @param {Boolean} options.fetchWhenSave fetch and update object after save succeeded
* @param {AV.Query} options.query Save object only when it matches the query
* @return {AV.Promise} A promise that is fulfilled when the save
* completes.
* @see AVError
*/
save: function(arg1, arg2, arg3) {
var i, attrs, current, options, saved;
if (_.isObject(arg1) || utils.isNullOrUndefined(arg1)) {
attrs = arg1;
options = arg2;
} else {
attrs = {};
attrs[arg1] = arg2;
options = arg3;
}
// Make save({ success: function() {} }) work.
if (!options && attrs) {
var extra_keys = _.reject(attrs, function(value, key) {
return _.include(["success", "error", "wait"], key);
});
if (extra_keys.length === 0) {
var all_functions = true;
if (_.has(attrs, "success") && !_.isFunction(attrs.success)) {
all_functions = false;
}
if (_.has(attrs, "error") && !_.isFunction(attrs.error)) {
all_functions = false;
}
if (all_functions) {
// This attrs object looks like it's really an options object,
// and there's no other options object, so let's just use it.
return this.save(null, attrs);
}
}
}
options = _.clone(options) || {};
if (options.wait) {
current = _.clone(this.attributes);
}
var setOptions = _.clone(options) || {};
if (setOptions.wait) {
setOptions.silent = true;
}
var setError;
setOptions.error = function(model, error) {
setError = error;
};
if (attrs && !this.set(attrs, setOptions)) {
return AV.Promise.error(setError)._thenRunCallbacks(options, this);
}
var model = this;
// If there is any unsaved child, save it first.
model._refreshCache();
var unsavedChildren = [];
var unsavedFiles = [];
AV.Object._findUnsavedChildren(model.attributes,
unsavedChildren,
unsavedFiles);
if (unsavedChildren.length + unsavedFiles.length > 0) {
return AV.Object._deepSaveAsync(this.attributes, model, options).then(function() {
return model.save(null, options);
}, function(error) {
return AV.Promise.error(error)._thenRunCallbacks(options, model);
});
}
this._startSave();
this._saving = (this._saving || 0) + 1;
this._allPreviousSaves = this._allPreviousSaves || AV.Promise.as();
this._allPreviousSaves = this._allPreviousSaves._continueWith(function() {
var method = model.id ? 'PUT' : 'POST';
var json = model._getSaveJSON();
if(model._fetchWhenSave){
//Sepcial-case fetchWhenSave when updating object.
json._fetchWhenSave = true;
}
if (options.fetchWhenSave) {
json._fetchWhenSave = true;
}
if (options.query) {
var queryJSON;
if (typeof options.query.toJSON === 'function') {
queryJSON = options.query.toJSON();
if (queryJSON) {
json._where = queryJSON.where;
}
}
if (!json._where) {
var error = new Error('options.query is not an AV.Query');
return AV.Promise.error(error)._thenRunCallbacks(options, model);
}
}
var route = "classes";
var className = model.className;
if (model.className === "_User" && !model.id) {
// Special-case user sign-up.
route = "users";
className = null;
}
//hook makeRequest in options.