-
-
Notifications
You must be signed in to change notification settings - Fork 594
/
Copy pathParseQuery.js
1052 lines (965 loc) · 34.5 KB
/
ParseQuery.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 encode from './encode';
import ParseError from './ParseError';
import ParseGeoPoint from './ParseGeoPoint';
import ParseObject from './ParseObject';
import ParsePromise from './ParsePromise';
import type { RequestOptions, FullOptions } from './RESTController';
type BatchOptions = FullOptions & { batchSize?: number };
export type WhereClause = {
[attr: string]: mixed;
};
export type QueryJSON = {
where: WhereClause;
include?: string;
keys?: string;
limit?: number;
skip?: number;
order?: string;
className?: string;
count?: number;
};
/**
* Converts a string into a regex that matches it.
* Surrounding with \Q .. \E does this, we just need to escape any \E's in
* the text separately.
*/
function quote(s: string) {
return '\\Q' + s.replace('\\E', '\\E\\\\E\\Q') + '\\E';
}
/**
* Creates a new parse Parse.Query for the given Parse.Object subclass.
* @class Parse.Query
* @constructor
* @param {} objectClass An instance of a subclass of Parse.Object, or a Parse className string.
*
* <p>Parse.Query defines a query that is used to fetch Parse.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 Parse.Query(MyClass);
* query.find({
* success: function(results) {
* // results is an array of Parse.Object.
* },
*
* error: function(error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*
* <p>A Parse.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 Parse.Query(MyClass);
* query.get(myId, {
* success: function(object) {
* // object is an instance of Parse.Object.
* },
*
* error: function(object, error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*
* <p>A Parse.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 Parse.Query(MyClass);
* query.count({
* success: function(number) {
* // There are number instances of MyClass.
* },
*
* error: function(error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*/
export default class ParseQuery {
className: string;
_where: any;
_include: Array<string>;
_select: Array<string>;
_limit: number;
_skip: number;
_order: Array<string>;
_extraOptions: { [key: string]: mixed };
constructor(objectClass: string | ParseObject) {
if (typeof objectClass === 'string') {
if (objectClass === 'User' && CoreManager.get('PERFORM_USER_REWRITE')) {
this.className = '_User';
} else {
this.className = objectClass;
}
} else if (objectClass instanceof ParseObject) {
this.className = objectClass.className;
} else if (typeof objectClass === 'function') {
if (typeof objectClass.className === 'string') {
this.className = objectClass.className;
} else {
var obj = new objectClass();
this.className = obj.className;
}
} else {
throw new TypeError(
'A ParseQuery must be constructed with a ParseObject or class name.'
);
}
this._where = {};
this._include = [];
this._limit = -1; // negative limit is not sent in the server request
this._skip = 0;
this._extraOptions = {};
}
/**
* Adds constraint that at least one of the passed in queries matches.
* @method _orQuery
* @param {Array} queries
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
_orQuery(queries: Array<ParseQuery>): ParseQuery {
var queryJSON = queries.map((q) => {
return q.toJSON().where;
});
this._where.$or = queryJSON;
return this;
}
/**
* Helper for condition queries
*/
_addCondition(key: string, condition: string, value: mixed): ParseQuery {
if (!this._where[key] || typeof this._where[key] === 'string') {
this._where[key] = {};
}
this._where[key][condition] = encode(value, false, true);
return this;
}
/**
* Returns a JSON representation of this query.
* @method toJSON
* @return {Object} The JSON representation of the query.
*/
toJSON(): QueryJSON {
var params: QueryJSON = {
where: this._where
};
if (this._include.length) {
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) {
params.order = this._order.join(',');
}
for (var key in this._extraOptions) {
params[key] = this._extraOptions[key];
}
return params;
}
/**
* Constructs a Parse.Object whose id is already known by fetching data from
* the server. Either options.success or options.error is called when the
* find completes.
*
* @method get
* @param {String} objectId The id of the object to be fetched.
* @param {Object} options A Backbone-style options object.
* Valid options are:<ul>
* <li>success: A Backbone-style success callback
* <li>error: An Backbone-style error callback.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the result when
* the query completes.
*/
get(objectId: string, options?: FullOptions): ParsePromise {
this.equalTo('objectId', objectId);
var firstOptions = {};
if (options && options.hasOwnProperty('useMasterKey')) {
firstOptions.useMasterKey = options.useMasterKey;
}
if (options && options.hasOwnProperty('sessionToken')) {
firstOptions.sessionToken = options.sessionToken;
}
return this.first(firstOptions).then((response) => {
if (response) {
return response;
}
var errorObject = new ParseError(
ParseError.OBJECT_NOT_FOUND,
'Object not found.'
);
return ParsePromise.error(errorObject);
})._thenRunCallbacks(options, null);
}
/**
* Retrieves a list of ParseObjects that satisfy this query.
* Either options.success or options.error is called when the find
* completes.
*
* @method find
* @param {Object} options A Backbone-style options object. Valid options
* are:<ul>
* <li>success: Function to call when the find completes successfully.
* <li>error: Function to call when the find fails.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the results when
* the query completes.
*/
find(options?: FullOptions): ParsePromise {
options = options || {};
let findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
let controller = CoreManager.getQueryController();
return controller.find(
this.className,
this.toJSON(),
findOptions
).then((response) => {
return response.results.map((data) => {
// In cases of relations, the server may send back a className
// on the top level of the payload
let override = response.className || this.className;
if (!data.className) {
data.className = override;
}
return ParseObject.fromJSON(data, true);
});
})._thenRunCallbacks(options);
}
/**
* Counts the number of objects that match this query.
* Either options.success or options.error is called when the count
* completes.
*
* @method count
* @param {Object} options A Backbone-style options object. Valid options
* are:<ul>
* <li>success: Function to call when the count completes successfully.
* <li>error: Function to call when the find fails.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the count when
* the query completes.
*/
count(options?: FullOptions): ParsePromise {
options = options || {};
var findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
var controller = CoreManager.getQueryController();
var params = this.toJSON();
params.limit = 0;
params.count = 1;
return controller.find(
this.className,
params,
findOptions
).then((result) => {
return result.count;
})._thenRunCallbacks(options);
}
/**
* Retrieves at most one Parse.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.
*
* @method first
* @param {Object} options A Backbone-style options object. Valid options
* are:<ul>
* <li>success: Function to call when the find completes successfully.
* <li>error: Function to call when the find fails.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the object when
* the query completes.
*/
first(options?: FullOptions): ParsePromise {
options = options || {};
var findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
var controller = CoreManager.getQueryController();
var params = this.toJSON();
params.limit = 1;
return controller.find(
this.className,
params,
findOptions
).then((response) => {
var objects = response.results;
if (!objects[0]) {
return undefined;
}
if (!objects[0].className) {
objects[0].className = this.className;
}
return ParseObject.fromJSON(objects[0], true);
})._thenRunCallbacks(options);
}
/**
* 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.
* @method each
* @param {Function} callback Callback that will be called with each result
* of the query.
* @param {Object} options A Backbone-style options object. Valid options
* are:<ul>
* <li>success: Function to call when the iteration completes successfully.
* <li>error: Function to call when the iteration fails.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
* @return {Parse.Promise} A promise that will be fulfilled once the
* iteration has completed.
*/
each(callback: (obj: ParseObject) => any, options?: BatchOptions): ParsePromise {
options = options || {};
if (this._order || this._skip || (this._limit >= 0)) {
var error = 'Cannot iterate on a query with sort, skip, or limit.';
return ParsePromise.error(error)._thenRunCallbacks(options);
}
var promise = new ParsePromise();
var query = new ParseQuery(this.className);
// We can override the batch size from the options.
// This is undocumented, but useful for testing.
query._limit = options.batchSize || 100;
query._include = this._include.map((i) => {
return i;
});
if (this._select) {
query._select = this._select.map((s) => {
return s;
});
}
query._where = {};
for (var attr in this._where) {
var val = this._where[attr];
if (Array.isArray(val)) {
query._where[attr] = val.map((v) => {
return v;
});
} else if (val && typeof val === 'object') {
var conditionMap = {};
query._where[attr] = conditionMap;
for (var cond in val) {
conditionMap[cond] = val[cond];
}
} else {
query._where[attr] = val;
}
}
query.ascending('objectId');
var findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
var finished = false;
return ParsePromise._continueWhile(() => {
return !finished;
}, () => {
return query.find(findOptions).then((results) => {
var callbacksDone = ParsePromise.as();
results.forEach((result) => {
callbacksDone = callbacksDone.then(() => {
return callback(result);
});
});
return callbacksDone.then(() => {
if (results.length >= query._limit) {
query.greaterThan('objectId', results[results.length - 1].id);
} else {
finished = true;
}
});
});
})._thenRunCallbacks(options);
}
/** Query Conditions **/
/**
* Adds a constraint to the query that requires a particular key's value to
* be equal to the provided value.
* @method equalTo
* @param {String} key The key to check.
* @param value The value that the Parse.Object must contain.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
equalTo(key: string, value: mixed): ParseQuery {
if (typeof value === 'undefined') {
return this.doesNotExist(key);
}
this._where[key] = encode(value, false, true);
return this;
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be not equal to the provided value.
* @method notEqualTo
* @param {String} key The key to check.
* @param value The value that must not be equalled.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
notEqualTo(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$ne', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be less than the provided value.
* @method lessThan
* @param {String} key The key to check.
* @param value The value that provides an upper bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
lessThan(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$lt', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be greater than the provided value.
* @method greaterThan
* @param {String} key The key to check.
* @param value The value that provides an lower bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
greaterThan(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$gt', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be less than or equal to the provided value.
* @method lessThanOrEqualTo
* @param {String} key The key to check.
* @param value The value that provides an upper bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
lessThanOrEqualTo(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$lte', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be greater than or equal to the provided value.
* @method greaterThanOrEqualTo
* @param {String} key The key to check.
* @param value The value that provides an lower bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
greaterThanOrEqualTo(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$gte', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be contained in the provided list of values.
* @method containedIn
* @param {String} key The key to check.
* @param {Array} values The values that will match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
containedIn(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$in', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* not be contained in the provided list of values.
* @method notContainedIn
* @param {String} key The key to check.
* @param {Array} values The values that will not match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
notContainedIn(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$nin', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* contain each one of the provided list of values.
* @method containsAll
* @param {String} key The key to check. This key's value must be an array.
* @param {Array} values The values that will match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
containsAll(key: string, values: Array<mixed>): ParseQuery {
return this._addCondition(key, '$all', values);
}
/**
* Adds a constraint for finding objects that contain the given key.
* @method exists
* @param {String} key The key that should exist.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
exists(key: string): ParseQuery {
return this._addCondition(key, '$exists', true);
}
/**
* Adds a constraint for finding objects that do not contain a given key.
* @method doesNotExist
* @param {String} key The key that should not exist
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotExist(key: string): ParseQuery {
return this._addCondition(key, '$exists', false);
}
/**
* Adds a regular expression constraint for finding string values that match
* the provided regular expression.
* This may be slow for large datasets.
* @method matches
* @param {String} key The key that the string to match is stored in.
* @param {RegExp} regex The regular expression pattern to match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
matches(key: string, regex: RegExp, modifiers: string): ParseQuery {
this._addCondition(key, '$regex', regex);
if (!modifiers) {
modifiers = '';
}
if (regex.ignoreCase) {
modifiers += 'i';
}
if (regex.multiline) {
modifiers += 'm';
}
if (modifiers.length) {
this._addCondition(key, '$options', modifiers);
}
return this;
}
/**
* Adds a constraint that requires that a key's value matches a Parse.Query
* constraint.
* @method matchesQuery
* @param {String} key The key that the contains the object to match the
* query.
* @param {Parse.Query} query The query that should match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
matchesQuery(key: string, query: ParseQuery): ParseQuery {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$inQuery', queryJSON);
}
/**
* Adds a constraint that requires that a key's value not matches a
* Parse.Query constraint.
* @method doesNotMatchQuery
* @param {String} key The key that the contains the object to match the
* query.
* @param {Parse.Query} query The query that should not match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotMatchQuery(key: string, query: ParseQuery): ParseQuery {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$notInQuery', queryJSON);
}
/**
* Adds a constraint that requires that a key's value matches a value in
* an object returned by a different Parse.Query.
* @method matchesKeyInQuery
* @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 {Parse.Query} query The query to run.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
matchesKeyInQuery(key: string, queryKey: string, query: ParseQuery): ParseQuery {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$select', {
key: queryKey,
query: queryJSON
});
}
/**
* Adds a constraint that requires that a key's value not match a value in
* an object returned by a different Parse.Query.
* @method doesNotMatchKeyInQuery
* @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 {Parse.Query} query The query to run.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotMatchKeyInQuery(key: string, queryKey: string, query: ParseQuery): ParseQuery {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$dontSelect', {
key: queryKey,
query: queryJSON
});
}
/**
* Adds a constraint for finding string values that contain a provided
* string. This may be slow for large datasets.
* @method contains
* @param {String} key The key that the string to match is stored in.
* @param {String} substring The substring that the value must contain.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
contains(key: string, value: string): ParseQuery {
if (typeof value !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this._addCondition(key, '$regex', quote(value));
}
/**
* Adds 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.
* @method startsWith
* @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 {Parse.Query} Returns the query, so you can chain this call.
*/
startsWith(key: string, value: string): ParseQuery {
if (typeof value !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this._addCondition(key, '$regex', '^' + quote(value));
}
/**
* Adds a constraint for finding string values that end with a provided
* string. This will be slow for large datasets.
* @method endsWith
* @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 {Parse.Query} Returns the query, so you can chain this call.
*/
endsWith(key: string, value: string): ParseQuery {
if (typeof value !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this._addCondition(key, '$regex', quote(value) + '$');
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given.
* @method near
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
near(key: string, point: ParseGeoPoint): ParseQuery {
if (!(point instanceof ParseGeoPoint)) {
// Try to cast it as a GeoPoint
point = new ParseGeoPoint(point);
}
return this._addCondition(key, '$nearSphere', point);
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* @method withinRadians
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in radians) of results to
* return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinRadians(key: string, point: ParseGeoPoint, distance: number): ParseQuery {
this.near(key, point);
return this._addCondition(key, '$maxDistance', distance);
}
/**
* Adds 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.
* @method withinMiles
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in miles) of results to
* return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinMiles(key: string, point: ParseGeoPoint, distance: number): ParseQuery {
return this.withinRadians(key, point, distance / 3958.8);
}
/**
* Adds 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.
* @method withinKilometers
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in kilometers) of results
* to return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinKilometers(key: string, point: ParseGeoPoint, distance: number): ParseQuery {
return this.withinRadians(key, point, distance / 6371.0);
}
/**
* Adds a constraint to the query that requires a particular key's
* coordinates be contained within a given rectangular geographic bounding
* box.
* @method withinGeoBox
* @param {String} key The key to be constrained.
* @param {Parse.GeoPoint} southwest
* The lower-left inclusive corner of the box.
* @param {Parse.GeoPoint} northeast
* The upper-right inclusive corner of the box.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinGeoBox(key: string, southwest: ParseGeoPoint, northeast: ParseGeoPoint): ParseQuery {
if (!(southwest instanceof ParseGeoPoint)) {
southwest = new ParseGeoPoint(southwest);
}
if (!(northeast instanceof ParseGeoPoint)) {
northeast = new ParseGeoPoint(northeast);
}
this._addCondition(key, '$within', { '$box': [ southwest, northeast ] });
return this;
}
/** Query Orderings **/
/**
* Sorts the results in ascending order by the given key.
*
* @method ascending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
ascending(...keys: Array<string>): ParseQuery {
this._order = [];
return this.addAscending.apply(this, keys);
}
/**
* Sorts the results in ascending order by the given key,
* but can also add secondary sort descriptors without overwriting _order.
*
* @method addAscending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
addAscending(...keys: Array<string>): ParseQuery {
if (!this._order) {
this._order = [];
}
keys.forEach((key) => {
if (Array.isArray(key)) {
key = key.join();
}
this._order = this._order.concat(key.replace(/\s/g, '').split(','));
});
return this;
}
/**
* Sorts the results in descending order by the given key.
*
* @method descending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
descending(...keys: Array<string>): ParseQuery {
this._order = [];
return this.addDescending.apply(this, keys);
}
/**
* Sorts the results in descending order by the given key,
* but can also add secondary sort descriptors without overwriting _order.
*
* @method addDescending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
addDescending(...keys: Array<string>): ParseQuery {
if (!this._order) {
this._order = [];
}
keys.forEach((key) => {
if (Array.isArray(key)) {
key = key.join();
}
this._order = this._order.concat(
key.replace(/\s/g, '').split(',').map((k) => {
return '-' + k;
})
);
});
return this;
}
/** Query Options **/
/**
* Sets the number of results to skip before returning any results.
* This is useful for pagination.
* Default is to skip zero results.
* @method skip
* @param {Number} n the number of results to skip.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
skip(n: number): ParseQuery {
if (typeof n !== 'number' || n < 0) {
throw new Error('You can only skip by a positive number');
}
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.
* @method limit
* @param {Number} n the number of results to limit to.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
limit(n: number): ParseQuery {
if (typeof n !== 'number') {
throw new Error('You can only set the limit to a numeric value');
}
this._limit = n;
return this;
}
/**
* Includes nested Parse.Objects for the provided key. You can use dot
* notation to specify which fields in the included object are also fetched.
* @method include
* @param {String} key The name of the key to include.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
include(...keys: Array<string>): ParseQuery {
keys.forEach((key) => {
if (Array.isArray(key)) {
this._include = this._include.concat(key);
} else {
this._include.push(key);
}
});
return this;
}
/**
* Restricts the fields of the returned Parse.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.
* @method select
* @param {Array} keys The names of the keys to include.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
select(...keys: Array<string>): ParseQuery {
if (!this._select) {
this._select = [];
}
keys.forEach((key) => {
if (Array.isArray(key)) {
this._select = this._select.concat(key);
} else {
this._select.push(key);
}
});
return this;
}
/**
* Subscribe this query to get liveQuery updates
* @method subscribe