forked from leancloud/javascript-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.js
More file actions
942 lines (857 loc) · 31.4 KB
/
Copy pathquery.js
File metadata and controls
942 lines (857 loc) · 31.4 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
/**
* 每位工程师都有保持代码优雅的义务
* Each engineer has a duty to keep the code elegant
**/
const _ = require('underscore');
const AVError = require('./error');
const AVRequest = require('./request').request;
// AV.Query is a way to create a list of AV.Objects.
module.exports = function(AV) {
/**
* Creates a new avoscloud AV.Query for the given AV.Object subclass.
* @param objectClass -
* An instance of a subclass of AV.Object, or a AV className string.
* @class
*
* <p>AV.Query defines a query that is used to fetch AV.Objects. The
* most common use case is finding all objects that match a query through the
* <code>find</code> method. For example, this sample code fetches all objects
* of class <code>MyClass</code>. It calls a different function depending on
* whether the fetch succeeded or not.
*
* <pre>
* var query = new AV.Query(MyClass);
* query.find({
* success: function(results) {
* // results is an array of AV.Object.
* },
*
* error: function(error) {
* // error is an instance of AVError.
* }
* });</pre></p>
*
* <p>A AV.Query can also be used to retrieve a single object whose id is
* known, through the get method. For example, this sample code fetches an
* object of class <code>MyClass</code> and id <code>myId</code>. It calls a
* different function depending on whether the fetch succeeded or not.
*
* <pre>
* var query = new AV.Query(MyClass);
* query.get(myId, {
* success: function(object) {
* // object is an instance of AV.Object.
* },
*
* error: function(object, error) {
* // error is an instance of AVError.
* }
* });</pre></p>
*
* <p>A AV.Query can also be used to count the number of objects that match
* the query without retrieving all of those objects. For example, this
* sample code counts the number of objects of the class <code>MyClass</code>
* <pre>
* var query = new AV.Query(MyClass);
* query.count({
* success: function(number) {
* // There are number instances of MyClass.
* },
*
* error: function(error) {
* // error is an instance of AVError.
* }
* });</pre></p>
*/
AV.Query = function(objectClass) {
if (_.isString(objectClass)) {
objectClass = AV.Object._getSubclass(objectClass);
}
this.objectClass = objectClass;
this.className = objectClass.prototype.className;
this._where = {};
this._include = [];
this._limit = -1; // negative limit means, do not send a limit
this._skip = 0;
this._extraOptions = {};
};
/**
* Constructs a AV.Query that is the OR of the passed in queries. For
* example:
* <pre>var compoundQuery = AV.Query.or(query1, query2, query3);</pre>
*
* will create a compoundQuery that is an or of the query1, query2, and
* query3.
* @param {...AV.Query} var_args The list of queries to OR.
* @return {AV.Query} The query that is the OR of the passed in queries.
*/
AV.Query.or = function() {
var queries = _.toArray(arguments);
var className = null;
AV._arrayEach(queries, function(q) {
if (_.isNull(className)) {
className = q.className;
}
if (className !== q.className) {
throw "All queries must be for the same class";
}
});
var query = new AV.Query(className);
query._orQuery(queries);
return query;
};
/**
* Constructs a AV.Query that is the AND of the passed in queries. For
* example:
* <pre>var compoundQuery = AV.Query.and(query1, query2, query3);</pre>
*
* will create a compoundQuery that is an 'and' of the query1, query2, and
* query3.
* @param {...AV.Query} var_args The list of queries to AND.
* @return {AV.Query} The query that is the AND of the passed in queries.
*/
AV.Query.and = function() {
var queries = _.toArray(arguments);
var className = null;
AV._arrayEach(queries, function(q) {
if (_.isNull(className)) {
className = q.className;
}
if (className !== q.className) {
throw "All queries must be for the same class";
}
});
var query = new AV.Query(className);
query._andQuery(queries);
return query;
};
/**
* Retrieves a list of AVObjects that satisfy the CQL.
* CQL syntax please see <a href='https://cn.avoscloud.com/docs/cql_guide.html'>CQL Guide.</a>
* Either options.success or options.error is called when the find
* completes.
*
* @param {String} cql, A CQL string, see <a href='https://cn.avoscloud.com/docs/cql_guide.html'>CQL Guide.</a>
* @param {Array} pvalues, An array contains placeholder values.
* @param {Object} options A Backbone-style options object,it's optional.
* @return {AV.Promise} A promise that is resolved with the results when
* the query completes,it's optional.
*/
AV.Query.doCloudQuery = function(cql, pvalues, options) {
var params = { cql: cql };
if(_.isArray(pvalues)){
params.pvalues = pvalues;
} else {
options = pvalues;
}
var request = AVRequest('cloudQuery', null, null, 'GET', params, options && options.sessionToken);
return request.then(function(response) {
//query to process results.
var query = new AV.Query(response.className);
var results = _.map(response.results, function(json) {
var obj = query._newObject(response);
obj._finishFetch(query._processResult(json), true);
return obj;
});
return {
results: results,
count: response.count,
className: response.className
};
})._thenRunCallbacks(options);
};
AV.Query._extend = AV._extend;
AV.Query.prototype = {
//hook to iterate result. Added by dennis<xzhuang@avoscloud.com>.
_processResult: function(obj){
return obj;
},
/**
* Constructs a AV.Object whose id is already known by fetching data from
* the server. Either options.success or options.error is called when the
* find completes.
*
* @param {} objectId The id of the object to be fetched.
* @param {Object} options A Backbone-style options object.
*/
get: function(objectId, options) {
if(!objectId) {
var errorObject = new AVError(AVError.OBJECT_NOT_FOUND,
"Object not found.");
throw errorObject;
}
var self = this;
self.equalTo('objectId', objectId);
return self.first().then(function(response) {
if (!_.isEmpty(response)) {
return response;
}
var errorObject = new AVError(AVError.OBJECT_NOT_FOUND,
"Object not found.");
return AV.Promise.error(errorObject);
})._thenRunCallbacks(options, null);
},
/**
* Returns a JSON representation of this query.
* @return {Object}
*/
toJSON: function() {
var params = {
where: this._where
};
if (this._include.length > 0) {
params.include = this._include.join(",");
}
if (this._select) {
params.keys = this._select.join(",");
}
if (this._limit >= 0) {
params.limit = this._limit;
}
if (this._skip > 0) {
params.skip = this._skip;
}
if (this._order !== undefined) {
params.order = this._order;
}
AV._objectEach(this._extraOptions, function(v, k) {
params[k] = v;
});
return params;
},
_newObject: function(response){
var obj;
if (response && response.className) {
obj = new AV.Object(response.className);
} else {
obj = new this.objectClass();
}
return obj;
},
_createRequest: function(params, options){
return AVRequest('classes', this.className, null, "GET",
params || this.toJSON(), options && options.sessionToken);
},
/**
* Retrieves a list of AVObjects that satisfy this query.
* Either options.success or options.error is called when the find
* completes.
*
* @param {Object} options A Backbone-style options object.
* @return {AV.Promise} A promise that is resolved with the results when
* the query completes.
*/
find: function(options) {
var self = this;
var request = this._createRequest(null, options);
return request.then(function(response) {
return _.map(response.results, function(json) {
var obj = self._newObject(response);
obj._finishFetch(self._processResult(json), true);
return obj;
});
})._thenRunCallbacks(options);
},
/**
* Delete objects retrieved by this query.
* @param {Object} options Standard options object with success and error
* callbacks.
* @return {AV.Promise} A promise that is fulfilled when the save
* completes.
*/
destroyAll: function(options){
var self = this;
return self.find().then(function(objects){
return AV.Object.destroyAll(objects);
})._thenRunCallbacks(options);
},
/**
* Counts the number of objects that match this query.
* Either options.success or options.error is called when the count
* completes.
*
* @param {Object} options A Backbone-style options object.
* @return {AV.Promise} A promise that is resolved with the count when
* the query completes.
*/
count: function(options) {
var params = this.toJSON();
params.limit = 0;
params.count = 1;
var request = this._createRequest(params, options);
return request.then(function(response) {
return response.count;
})._thenRunCallbacks(options);
},
/**
* Retrieves at most one AV.Object that satisfies this query.
*
* Either options.success or options.error is called when it completes.
* success is passed the object if there is one. otherwise, undefined.
*
* @param {Object} options A Backbone-style options object.
* @return {AV.Promise} A promise that is resolved with the object when
* the query completes.
*/
first: function(options) {
var self = this;
var params = this.toJSON();
params.limit = 1;
var request = this._createRequest(params, options);
return request.then(function(response) {
return _.map(response.results, function(json) {
var obj = self._newObject();
obj._finishFetch(self._processResult(json), true);
return obj;
})[0];
})._thenRunCallbacks(options);
},
/**
* Returns a new instance of AV.Collection backed by this query.
* @return {AV.Collection}
*/
collection: function(items, options) {
options = options || {};
return new AV.Collection(items, _.extend(options, {
model: this._objectClass || this.objectClass,
query: this
}));
},
/**
* Sets the number of results to skip before returning any results.
* This is useful for pagination.
* Default is to skip zero results.
* @param {Number} n the number of results to skip.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
skip: function(n) {
this._skip = n;
return this;
},
/**
* Sets the limit of the number of results to return. The default limit is
* 100, with a maximum of 1000 results being returned at a time.
* @param {Number} n the number of results to limit to.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
limit: function(n) {
this._limit = n;
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be equal to the provided value.
* @param {String} key The key to check.
* @param value The value that the AV.Object must contain.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
equalTo: function(key, value) {
this._where[key] = AV._encode(value);
return this;
},
/**
* Helper for condition queries
*/
_addCondition: function(key, condition, value) {
// Check if we already have a condition
if (!this._where[key]) {
this._where[key] = {};
}
this._where[key][condition] = AV._encode(value);
return this;
},
/**
* Add a constraint to the query that requires a particular
* <strong>array</strong> key's length to be equal to the provided value.
* @param {String} key The array key to check.
* @param value The length value.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
sizeEqualTo: function(key, value) {
this._addCondition(key, "$size", value);
},
/**
* Add a constraint to the query that requires a particular key's value to
* be not equal to the provided value.
* @param {String} key The key to check.
* @param value The value that must not be equalled.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
notEqualTo: function(key, value) {
this._addCondition(key, "$ne", value);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be less than the provided value.
* @param {String} key The key to check.
* @param value The value that provides an upper bound.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
lessThan: function(key, value) {
this._addCondition(key, "$lt", value);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be greater than the provided value.
* @param {String} key The key to check.
* @param value The value that provides an lower bound.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
greaterThan: function(key, value) {
this._addCondition(key, "$gt", value);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be less than or equal to the provided value.
* @param {String} key The key to check.
* @param value The value that provides an upper bound.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
lessThanOrEqualTo: function(key, value) {
this._addCondition(key, "$lte", value);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be greater than or equal to the provided value.
* @param {String} key The key to check.
* @param value The value that provides an lower bound.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
greaterThanOrEqualTo: function(key, value) {
this._addCondition(key, "$gte", value);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be contained in the provided list of values.
* @param {String} key The key to check.
* @param {Array} values The values that will match.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
containedIn: function(key, values) {
this._addCondition(key, "$in", values);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* not be contained in the provided list of values.
* @param {String} key The key to check.
* @param {Array} values The values that will not match.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
notContainedIn: function(key, values) {
this._addCondition(key, "$nin", values);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* contain each one of the provided list of values.
* @param {String} key The key to check. This key's value must be an array.
* @param {Array} values The values that will match.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
containsAll: function(key, values) {
this._addCondition(key, "$all", values);
return this;
},
/**
* Add a constraint for finding objects that contain the given key.
* @param {String} key The key that should exist.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
exists: function(key) {
this._addCondition(key, "$exists", true);
return this;
},
/**
* Add a constraint for finding objects that do not contain a given key.
* @param {String} key The key that should not exist
* @return {AV.Query} Returns the query, so you can chain this call.
*/
doesNotExist: function(key) {
this._addCondition(key, "$exists", false);
return this;
},
/**
* Add a regular expression constraint for finding string values that match
* the provided regular expression.
* This may be slow for large datasets.
* @param {String} key The key that the string to match is stored in.
* @param {RegExp} regex The regular expression pattern to match.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
matches: function(key, regex, modifiers) {
this._addCondition(key, "$regex", regex);
if (!modifiers) { modifiers = ""; }
// Javascript regex options support mig as inline options but store them
// as properties of the object. We support mi & should migrate them to
// modifiers
if (regex.ignoreCase) { modifiers += 'i'; }
if (regex.multiline) { modifiers += 'm'; }
if (modifiers && modifiers.length) {
this._addCondition(key, "$options", modifiers);
}
return this;
},
/**
* Add a constraint that requires that a key's value matches a AV.Query
* constraint.
* @param {String} key The key that the contains the object to match the
* query.
* @param {AV.Query} query The query that should match.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
matchesQuery: function(key, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
this._addCondition(key, "$inQuery", queryJSON);
return this;
},
/**
* Add a constraint that requires that a key's value not matches a
* AV.Query constraint.
* @param {String} key The key that the contains the object to match the
* query.
* @param {AV.Query} query The query that should not match.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
doesNotMatchQuery: function(key, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
this._addCondition(key, "$notInQuery", queryJSON);
return this;
},
/**
* Add a constraint that requires that a key's value matches a value in
* an object returned by a different AV.Query.
* @param {String} key The key that contains the value that is being
* matched.
* @param {String} queryKey The key in the objects returned by the query to
* match against.
* @param {AV.Query} query The query to run.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
matchesKeyInQuery: function(key, queryKey, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
this._addCondition(key, "$select",
{ key: queryKey, query: queryJSON });
return this;
},
/**
* Add a constraint that requires that a key's value not match a value in
* an object returned by a different AV.Query.
* @param {String} key The key that contains the value that is being
* excluded.
* @param {String} queryKey The key in the objects returned by the query to
* match against.
* @param {AV.Query} query The query to run.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
doesNotMatchKeyInQuery: function(key, queryKey, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
this._addCondition(key, "$dontSelect",
{ key: queryKey, query: queryJSON });
return this;
},
/**
* Add constraint that at least one of the passed in queries matches.
* @param {Array} queries
* @return {AV.Query} Returns the query, so you can chain this call.
*/
_orQuery: function(queries) {
var queryJSON = _.map(queries, function(q) {
return q.toJSON().where;
});
this._where.$or = queryJSON;
return this;
},
/**
* Add constraint that both of the passed in queries matches.
* @param {Array} queries
* @return {AV.Query} Returns the query, so you can chain this call.
*/
_andQuery: function(queries) {
var queryJSON = _.map(queries, function(q) {
return q.toJSON().where;
});
this._where.$and = queryJSON;
return this;
},
/**
* Converts a string into a regex that matches it.
* Surrounding with \Q .. \E does this, we just need to escape \E's in
* the text separately.
*/
_quote: function(s) {
return "\\Q" + s.replace("\\E", "\\E\\\\E\\Q") + "\\E";
},
/**
* Add a constraint for finding string values that contain a provided
* string. This may be slow for large datasets.
* @param {String} key The key that the string to match is stored in.
* @param {String} substring The substring that the value must contain.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
contains: function(key, value) {
this._addCondition(key, "$regex", this._quote(value));
return this;
},
/**
* Add a constraint for finding string values that start with a provided
* string. This query will use the backend index, so it will be fast even
* for large datasets.
* @param {String} key The key that the string to match is stored in.
* @param {String} prefix The substring that the value must start with.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
startsWith: function(key, value) {
this._addCondition(key, "$regex", "^" + this._quote(value));
return this;
},
/**
* Add a constraint for finding string values that end with a provided
* string. This will be slow for large datasets.
* @param {String} key The key that the string to match is stored in.
* @param {String} suffix The substring that the value must end with.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
endsWith: function(key, value) {
this._addCondition(key, "$regex", this._quote(value) + "$");
return this;
},
/**
* Sorts the results in ascending order by the given key.
*
* @param {String} key The key to order by.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
ascending: function(key) {
this._order = key;
return this;
},
/**
* Also sorts the results in ascending order by the given key. The previous sort keys have
* precedence over this key.
*
* @param {String} key The key to order by
* @return {AV.Query} Returns the query so you can chain this call.
*/
addAscending: function(key){
if(this._order)
this._order += ',' + key;
else
this._order = key;
return this;
},
/**
* Sorts the results in descending order by the given key.
*
* @param {String} key The key to order by.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
descending: function(key) {
this._order = "-" + key;
return this;
},
/**
* Also sorts the results in descending order by the given key. The previous sort keys have
* precedence over this key.
*
* @param {String} key The key to order by
* @return {AV.Query} Returns the query so you can chain this call.
*/
addDescending: function(key){
if(this._order)
this._order += ',-' + key;
else
this._order = '-' + key;
return key;
},
/**
* Add a proximity based constraint for finding objects with key point
* values near the point given.
* @param {String} key The key that the AV.GeoPoint is stored in.
* @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
near: function(key, point) {
if (!(point instanceof AV.GeoPoint)) {
// Try to cast it to a GeoPoint, so that near("loc", [20,30]) works.
point = new AV.GeoPoint(point);
}
this._addCondition(key, "$nearSphere", point);
return this;
},
/**
* Add a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* @param {String} key The key that the AV.GeoPoint is stored in.
* @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.
* @param maxDistance Maximum distance (in radians) of results to return.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
withinRadians: function(key, point, distance) {
this.near(key, point);
this._addCondition(key, "$maxDistance", distance);
return this;
},
/**
* Add a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* Radius of earth used is 3958.8 miles.
* @param {String} key The key that the AV.GeoPoint is stored in.
* @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in miles) of results to
* return.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
withinMiles: function(key, point, distance) {
return this.withinRadians(key, point, distance / 3958.8);
},
/**
* Add a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* Radius of earth used is 6371.0 kilometers.
* @param {String} key The key that the AV.GeoPoint is stored in.
* @param {AV.GeoPoint} point The reference AV.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in kilometers) of results
* to return.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
withinKilometers: function(key, point, distance) {
return this.withinRadians(key, point, distance / 6371.0);
},
/**
* Add a constraint to the query that requires a particular key's
* coordinates be contained within a given rectangular geographic bounding
* box.
* @param {String} key The key to be constrained.
* @param {AV.GeoPoint} southwest
* The lower-left inclusive corner of the box.
* @param {AV.GeoPoint} northeast
* The upper-right inclusive corner of the box.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
withinGeoBox: function(key, southwest, northeast) {
if (!(southwest instanceof AV.GeoPoint)) {
southwest = new AV.GeoPoint(southwest);
}
if (!(northeast instanceof AV.GeoPoint)) {
northeast = new AV.GeoPoint(northeast);
}
this._addCondition(key, '$within', { '$box': [southwest, northeast] });
return this;
},
/**
* Include nested AV.Objects for the provided key. You can use dot
* notation to specify which fields in the included object are also fetch.
* @param {String} key The name of the key to include.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
include: function() {
var self = this;
AV._arrayEach(arguments, function(key) {
if (_.isArray(key)) {
self._include = self._include.concat(key);
} else {
self._include.push(key);
}
});
return this;
},
/**
* Restrict the fields of the returned AV.Objects to include only the
* provided keys. If this is called multiple times, then all of the keys
* specified in each of the calls will be included.
* @param {Array} keys The names of the keys to include.
* @return {AV.Query} Returns the query, so you can chain this call.
*/
select: function() {
var self = this;
this._select = this._select || [];
AV._arrayEach(arguments, function(key) {
if (_.isArray(key)) {
self._select = self._select.concat(key);
} else {
self._select.push(key);
}
});
return this;
},
/**
* Iterates over each result of a query, calling a callback for each one. If
* the callback returns a promise, the iteration will not continue until
* that promise has been fulfilled. If the callback returns a rejected
* promise, then iteration will stop with that error. The items are
* processed in an unspecified order. The query may not have any sort order,
* and may not use limit or skip.
* @param callback {Function} Callback that will be called with each result
* of the query.
* @param options {Object} An optional Backbone-like options object with
* success and error callbacks that will be invoked once the iteration
* has finished.
* @return {AV.Promise} A promise that will be fulfilled once the
* iteration has completed.
*/
each: function(callback, options) {
options = options || {};
if (this._order || this._skip || (this._limit >= 0)) {
var error =
"Cannot iterate on a query with sort, skip, or limit.";
return AV.Promise.error(error)._thenRunCallbacks(options);
}
var promise = new AV.Promise();
var query = new AV.Query(this.objectClass);
// We can override the batch size from the options.
// This is undocumented, but useful for testing.
query._limit = options.batchSize || 100;
query._where = _.clone(this._where);
query._include = _.clone(this._include);
query.ascending('objectId');
var finished = false;
return AV.Promise._continueWhile(function() {
return !finished;
}, function() {
return query.find().then(function(results) {
var callbacksDone = AV.Promise.as();
_.each(results, function(result) {
callbacksDone = callbacksDone.then(function() {
return callback(result);
});
});
return callbacksDone.then(function() {
if (results.length >= query._limit) {
query.greaterThan("objectId", results[results.length - 1].id);
} else {
finished = true;
}
});
});
})._thenRunCallbacks(options);
}
};
AV.FriendShipQuery = AV.Query._extend({
_objectClass: AV.User,
_newObject: function(){
return new AV.User();
},
_processResult: function(json){
if(json && json[this._friendshipTag]) {
var user = json[this._friendshipTag];
if(user.__type === 'Pointer' && user.className === '_User'){
delete user.__type;
delete user.className;
}
return user;
} else {
return null;
}
},
});
};