forked from 418sec/js-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuery.ts
1181 lines (1146 loc) · 37 KB
/
Query.ts
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
import utils from './utils'
import Component from './Component'
const DOMAIN = 'Query'
const INDEX_ERR = 'Index inaccessible after first operation'
// Reserved words used by JSData's Query Syntax
const reserved = {
limit: '',
offset: '',
orderBy: '',
skip: '',
sort: '',
where: '',
locale: ''
}
// Used by our JavaScript implementation of the LIKE operator
const escapeRegExp = /([.*+?^=!:${}()|[\]/\\])/g
const percentRegExp = /%/g
const underscoreRegExp = /_/g
function escape (pattern) {
return pattern.replace(escapeRegExp, '\\$1')
}
export interface QueryDefinition {
[attr: string]: any
where?: any
orderBy?: any
sort?: any
skip?: number
limit?: number
offset?: number
}
/**
* A class used by the {@link Collection} class to build queries to be executed
* against the collection's data. An instance of `Query` is returned by
* {@link Collection#query}. Query instances are typically short-lived, and you
* shouldn't have to create them yourself. Just use {@link Collection#query}.
*
* ```javascript
* import { Query } from 'js-data';
* ```
*
* @example <caption>Query intro</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('post');
* const posts = [
* { author: 'John', age: 30, status: 'published', id: 1 },
* { author: 'Sally', age: 31, status: 'draft', id: 2 },
* { author: 'Mike', age: 32, status: 'draft', id: 3 },
* { author: 'Adam', age: 33, status: 'deleted', id: 4 },
* { author: 'Adam', age: 33, status: 'draft', id: 5 }
* ]
* store.add('post', posts);
* const drafts = store.query('post').filter({ status: 'draft' }).limit(2).run();
* console.log(drafts);
*
* @class Query
* @extends Component
* @param {Collection} collection The collection on which this query operates.
* @since 3.0.0
*/
export default class Query extends Component {
/**
* The current data result of this query.
*
* @name Query#data
* @since 3.0.0
* @type {Array}
*/
private data = null;
constructor (public collection?) {
super()
}
_applyWhereFromObject (where) {
const fields = []
const ops = []
const predicates = []
utils.forOwn(where, (clause, field) => {
if (!utils.isObject(clause)) {
clause = {
'==': clause
}
}
utils.forOwn(clause, (expr, op) => {
fields.push(field)
ops.push(op)
predicates.push(expr)
})
})
return {
fields,
ops,
predicates
}
}
_applyWhereFromArray (where) {
const groups: any = []
where.forEach((_where, i) => {
if (utils.isString(_where)) {
return
}
const prev = where[i - 1]
const parser = utils.isArray(_where) ? this._applyWhereFromArray : this._applyWhereFromObject
const group = parser.call(this, _where)
if (prev === 'or') {
group.isOr = true
}
groups.push(group)
})
groups.isArray = true
return groups
}
_testObjectGroup (keep, first, group, item) {
let i
const fields = group.fields
const ops = group.ops
const predicates = group.predicates
const len = ops.length
for (i = 0; i < len; i++) {
let op = ops[i]
const isOr = op.charAt(0) === '|'
op = isOr ? op.substr(1) : op
const expr = this.evaluate(utils.get(item, fields[i]), op, predicates[i])
if (expr !== undefined) {
keep = first ? expr : isOr ? keep || expr : keep && expr
}
first = false
}
return { keep, first }
}
_testArrayGroup (keep, first, groups, item) {
let i
const len = groups.length
for (i = 0; i < len; i++) {
const group = groups[i]
const parser = group.isArray ? this._testArrayGroup : this._testObjectGroup
const result = parser.call(this, true, true, group, item)
if (groups[i - 1]) {
if (group.isOr) {
keep = keep || result.keep
} else {
keep = keep && result.keep
}
} else {
keep = result.keep
}
first = result.first
}
return { keep, first }
}
/**
* Find all entities between two boundaries.
*
* @example <caption>Get the users ages 18 to 30.</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('user');
* const users = [
* { name: 'Peter', age: 25, id: 1 },
* { name: 'Jim', age: 19, id: 2 },
* { name: 'Mike', age: 17, id: 3 },
* { name: 'Alan', age: 29, id: 4 },
* { name: 'Katie', age: 33, id: 5 }
* ];
* store.add('user', users)
* const filteredUsers = store
* .query('user')
* .between(18, 30, { index: 'age' })
* .run();
* console.log(filteredUsers);
*
* @example <caption>Same as above.</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('user');
* const users = [
* { name: 'Peter', age: 25, id: 1 },
* { name: 'Jim', age: 19, id: 2 },
* { name: 'Mike', age: 17, id: 3 },
* { name: 'Alan', age: 29, id: 4 },
* { name: 'Katie', age: 33, id: 5 }
* ];
* store.add('user', users)
* const filteredUsers = store
* .query('user')
* .between([18], [30], { index: 'age' })
* .run();
* console.log(filteredUsers);
*
* @method Query#between
* @param {array} leftKeys Keys defining the left boundary.
* @param {array} rightKeys Keys defining the right boundary.
* @param {object} [opts] Configuration options.
* @param {string} [opts.index] Name of the secondary index to use in the
* query. If no index is specified, the main index is used.
* @param {boolean} [opts.leftInclusive=true] Whether to include entities
* on the left boundary.
* @param {boolean} [opts.rightInclusive=false] Whether to include entities
* on the left boundary.
* @param {boolean} [opts.limit] Limit the result to a certain number.
* @param {boolean} [opts.offset] The number of resulting entities to skip.
* @returns {Query} A reference to itself for chaining.
* @since 3.0.0
*/
between (leftKeys?, rightKeys?, opts: any = {}) {
if (this.data) {
throw utils.err(`${DOMAIN}#between`)(500, 'Cannot access index')
}
this.data = this.collection.getIndex(opts.index).between(leftKeys, rightKeys, opts)
return this
}
/**
* The comparison function used by the {@link Query} class.
*
* @method Query#compare
* @param {array} orderBy An orderBy clause used for sorting and sub-sorting.
* @param {number} index The index of the current orderBy clause being used.
* @param {*} a The first item in the comparison.
* @param {*} b The second item in the comparison.
* @returns {number} -1 if `b` should preceed `a`. 0 if `a` and `b` are equal.
* 1 if `a` should preceed `b`.
* @since 3.0.0
*/
compare (orderBy, index, a, b, compare) {
const def = orderBy[index]
let cA = utils.get(a, def[0])
let cB = utils.get(b, def[0])
if (cA && utils.isString(cA)) {
cA = cA.toUpperCase()
}
if (cB && utils.isString(cB)) {
cB = cB.toUpperCase()
}
if (a === undefined) {
a = null
}
if (b === undefined) {
b = null
}
if (def[1].toUpperCase() === 'DESC') {
const temp = cB
cB = cA
cA = temp
}
/* Fix: compare by using collator */
// let isNumeric = false
// if (utils.isNumber(cA) || utils.isNumber(cB)) {
// isNumeric = true
// }
const n = compare(cA, cB)
if (n === -1 || n === 1) {
return n
} else {
if (index < orderBy.length - 1) {
return this.compare(orderBy, index + 1, a, b, compare)
} else {
return 0
}
}
}
/**
* Predicate evaluation function used by the {@link Query} class.
*
* @method Query#evaluate
* @param {*} value The value to evaluate.
* @param {string} op The operator to use in this evaluation.
* @param {*} predicate The predicate to use in this evaluation.
* @returns {boolean} Whether the value passed the evaluation or not.
* @since 3.0.0
*/
evaluate (value, op, predicate) {
const ops = Query.ops
if (ops[op]) {
return ops[op](value, predicate)
}
if (op.indexOf('like') === 0) {
return this.like(predicate, op.substr(4)).exec(value) !== null
} else if (op.indexOf('notLike') === 0) {
return this.like(predicate, op.substr(7)).exec(value) === null
}
}
/**
* Find the record or records that match the provided query or are accepted by
* the provided filter function.
*
* @example <caption>Get the draft posts by authors younger than 30</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('post')
* const posts = [
* { author: 'John', age: 30, status: 'published', id: 1 },
* { author: 'Sally', age: 31, status: 'published', id: 2 },
* { author: 'Mike', age: 32, status: 'draft', id: 3 },
* { author: 'Adam', age: 33, status: 'deleted', id: 4 },
* { author: 'Adam', age: 33, status: 'published', id: 5 }
* { author: 'Peter', age: 25, status: 'deleted', id: 6 },
* { author: 'Sally', age: 21, status: 'draft', id: 7 },
* { author: 'Jim', age: 27, status: 'draft', id: 8 },
* { author: 'Jim', age: 27, status: 'published', id: 9 },
* { author: 'Jason', age: 55, status: 'published', id: 10 }
* ];
* store.add('post', posts);
* const results = store
* .query('post')
* .filter({
* where: {
* status: {
* '==': 'draft'
* },
* age: {
* '<': 30
* }
* }
* })
* .run();
* console.log(results);
*
* @example <caption>Use a custom filter function</caption>
* const posts = query
* .filter(function (post) {
* return post.isReady();
* })
* .run();
*
* @method Query#filter
* @param {(Object|Function)} [query={}] Selection query or filter
* function.
* @param {Function} [thisArg] Context to which to bind `queryOrFn` if
* `queryOrFn` is a function.
* @returns {Query} A reference to itself for chaining.
* @since 3.0.0
*/
filter (query: QueryDefinition = {}, thisArg?: Function): Query {
/**
* Selection query as defined by JSData's [Query Syntax][querysyntax].
*
* [querysyntax]: http://www.js-data.io/v3.0/docs/query-syntax
*
* @example <caption>Empty "findAll" query</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('post')
* store.findAll('post').then((posts) => {
* console.log(posts); // [...]
* });
*
* @example <caption>Empty "filter" query</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('post');
* const posts = store.filter('post');
* console.log(posts); // [...]
*
* @example <caption>Complex "filter" query</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* const PAGE_SIZE = 2;
* let currentPage = 3;
*
* store.defineMapper('post');
* const posts = [
* { author: 'John', age: 30, status: 'published', id: 1 },
* { author: 'Sally', age: 31, status: 'published', id: 2 },
* { author: 'Mike', age: 32, status: 'draft', id: 3 },
* { author: 'Adam', age: 33, status: 'deleted', id: 4 },
* { author: 'Adam', age: 33, status: 'published', id: 5 }
* { author: 'Peter', age: 25, status: 'deleted', id: 6 },
* { author: 'Sally', age: 21, status: 'draft', id: 7 },
* { author: 'Jim', age: 27, status: 'draft', id: 8 },
* { author: 'Jim', age: 27, status: 'published', id: 9 },
* { author: 'Jason', age: 55, status: 'published', id: 10 }
* ];
* store.add('post', posts);
* // Retrieve a filtered page of blog posts
* // Would typically replace filter with findAll
* const results = store.filter('post', {
* where: {
* status: {
* // WHERE status = 'published'
* '==': 'published'
* },
* author: {
* // AND author IN ('bob', 'alice')
* 'in': ['bob', 'alice'],
* // OR author IN ('karen')
* '|in': ['karen']
* }
* },
* orderBy: [
* // ORDER BY date_published DESC,
* ['date_published', 'DESC'],
* // ORDER BY title ASC
* ['title', 'ASC']
* ],
* // LIMIT 2
* limit: PAGE_SIZE,
* // SKIP 4
* offset: PAGE_SIZE * (currentPage - 1)
* });
* console.log(results);
*
* @namespace query
* @property {number} [limit] See {@link query.limit}.
* @property {number} [offset] See {@link query.offset}.
* @property {string|Array[]} [orderBy] See {@link query.orderBy}.
* @property {number} [skip] Alias for {@link query.offset}.
* @property {string|Array[]} [sort] Alias for {@link query.orderBy}.
* @property {Object} [where] See {@link query.where}.
* @property {String} [locale] See {@link query.locale}.
* @since 3.0.0
* @tutorial ["http://www.js-data.io/v3.0/docs/query-syntax","JSData's Query Syntax"]
*/
this.getData()
if (utils.isObject(query)) {
let where = {}
/**
* Filtering criteria. Records that do not meet this criteria will be exluded
* from the result.
*
* @example <caption>Return posts where author is at least 32 years old</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('post')
* const posts = [
* { author: 'John', age: 30, id: 5 },
* { author: 'Sally', age: 31, id: 6 },
* { author: 'Mike', age: 32, id: 7 },
* { author: 'Adam', age: 33, id: 8 },
* { author: 'Adam', age: 33, id: 9 }
* ];
* store.add('post', posts);
* const results = store.filter('post', {
* where: {
* age: {
* '>=': 30
* }
* }
* });
* console.log(results);
*
* @name query.where
* @type {Object}
* @see http://www.js-data.io/v3.0/docs/query-syntax
* @since 3.0.0
*/
if (utils.isObject(query.where) || utils.isArray(query.where)) {
where = query.where
}
utils.forOwn(query, (value, key) => {
if (!(key in reserved) && !(key in where)) {
where[key] = {
'==': value
}
}
})
let groups
// Apply filter for each field
if (utils.isObject(where) && Object.keys(where).length !== 0) {
groups = this._applyWhereFromArray([where])
} else if (utils.isArray(where)) {
groups = this._applyWhereFromArray(where)
}
if (groups) {
this.data = this.data.filter(item => this._testArrayGroup(true, true, groups, item).keep)
}
// Sort
let orderBy = query.orderBy || query.sort
if (utils.isString(orderBy)) {
orderBy = [[orderBy, 'ASC']]
}
if (!utils.isArray(orderBy)) {
orderBy = null
}
/**
* Determines how records should be ordered in the result.
*
* @example <caption>Order posts by `author` then by `id` descending </caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('post')
* const posts = [
* { author: 'John', age: 30, id: 5 },
* { author: 'Sally', age: 31, id: 6 },
* { author: 'Mike', age: 32, id: 7 },
* { author: 'Adam', age: 33, id: 8 },
* { author: 'Adam', age: 33, id: 9 }
* ];
* store.add('post', posts);
* const results = store.filter('post', {
* orderBy:[['author','ASC'],['id','DESC']]
* });
* console.log(results);
*
* @name query.orderBy
* @type {string|Array[]}
* @see http://www.js-data.io/v3.0/docs/query-syntax
* @since 3.0.0
*/
if (orderBy) {
const index = 0
orderBy.forEach((def, i) => {
if (utils.isString(def)) {
orderBy[i] = [def, 'ASC']
}
})
let locale: string = utils.getDefaultLocale()
if (utils.isString(query.locale)) {
locale = query.locale
}
/** The locale params has to be explicitly set for the collator.compare to work.
*
* @example <caption>Order posts with specific locale, defaults to 'en'</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('post')
* const posts = [
* { author: 'คลอน', age: 30, id: 5 },
* { author: 'กลอน', age: 31, id: 6 },
* { author: 'สาระ', age: 32, id: 7 },
* { author: 'ศาลา', age: 33, id: 8 },
* { author: 'จักรพรรณ', age: 33, id: 9 }
* ];
* store.add('post', posts);
* const results = store.filter('post', {
* orderBy:[['author','ASC'],['id','DESC']],
* locale: 'th'
* });
* console.log(results);
*
* @name query.locale
* @type {string}
* @see http://www.js-data.io/v4.0/docs/query-syntax
* @since 4.0.0
*/
const collator = new Intl.Collator(locale, {
numeric: true
})
this.data.sort((a, b) => this.compare(orderBy, index, a, b, collator.compare))
}
/**
* Number of records to skip.
*
* @example <caption>Retrieve the first "page" of blog posts using findAll</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('post');
* const PAGE_SIZE = 10;
* let currentPage = 1;
* store.findAll('post', {
* offset: PAGE_SIZE * (currentPage 1)
* limit: PAGE_SIZE
* });
*
* @example <caption>Retrieve the last "page" of blog posts using filter</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
*
* const PAGE_SIZE = 5;
* let currentPage = 2;
* store.defineMapper('post');
* const posts = [
* { author: 'John', age: 30, id: 1 },
* { author: 'Sally', age: 31, id: 2 },
* { author: 'Mike', age: 32, id: 3 },
* { author: 'Adam', age: 33, id: 4 },
* { author: 'Adam', age: 33, id: 5 },
* { author: 'Peter', age: 25, id: 6 },
* { author: 'Sally', age: 21, id: 7 },
* { author: 'Jim', age: 27, id: 8 },
* { author: 'Jim', age: 27, id: 9 },
* { author: 'Jason', age: 55, id: 10 }
* ];
* store.add('post', posts);
* const results = store.filter('post', {
* offset: PAGE_SIZE * (currentPage 1)
* limit: PAGE_SIZE
* });
* console.log(results)
*
* @name query.offset
* @type {number}
* @see http://www.js-data.io/v3.0/docs/query-syntax
* @since 3.0.0
*/
if (utils.isNumber(query.skip)) {
this.skip(query.skip)
} else if (utils.isNumber(query.offset)) {
this.skip(query.offset)
}
/**
* Maximum number of records to retrieve.
*
* @example <caption>Retrieve the first "page" of blog posts using findAll</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('post');
*
* const PAGE_SIZE = 10
* let currentPage = 1
* store.findAll('post', {
* offset: PAGE_SIZE * (currentPage 1)
* limit: PAGE_SIZE
* });
*
* @example <caption>Retrieve the last "page" of blog posts using filter</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
*
* const PAGE_SIZE = 5
* let currentPage = 2
* store.defineMapper('post')
* const posts = [
* { author: 'John', age: 30, id: 1 },
* { author: 'Sally', age: 31, id: 2 },
* { author: 'Mike', age: 32, id: 3 },
* { author: 'Adam', age: 33, id: 4 },
* { author: 'Adam', age: 33, id: 5 },
* { author: 'Peter', age: 25, id: 6 },
* { author: 'Sally', age: 21, id: 7 },
* { author: 'Jim', age: 27, id: 8 },
* { author: 'Jim', age: 27, id: 9 },
* { author: 'Jason', age: 55, id: 10 }
* ];
* store.add('post', posts);
* const results = store.filter('post', {
* offset: PAGE_SIZE * (currentPage 1)
* limit: PAGE_SIZE
* });
* console.log(results)
*
* @name query.limit
* @type {number}
* @see http://www.js-data.io/v3.0/docs/query-syntax
* @since 3.0.0
*/
if (utils.isNumber(query.limit)) {
this.limit(query.limit)
}
} else if (utils.isFunction(query)) {
this.data = this.data.filter(query, thisArg)
}
return this
}
/**
* Iterate over all entities.
*
* @method Query#forEach
* @param {Function} forEachFn Iteration function.
* @param {*} [thisArg] Context to which to bind `forEachFn`.
* @returns {Query} A reference to itself for chaining.
* @since 3.0.0
*/
forEach (forEachFn: Function, thisArg?) {
this.getData().forEach(forEachFn, thisArg)
return this
}
/**
* Find the entity or entities that match the provided key.
*
* @example <caption>Get the entity whose primary key is 25.</caption>
* const entities = query.get(25).run();
*
* @example <caption>Same as above.</caption>
* const entities = query.get([25]).run();
*
* @example <caption>Get all users who are active and have the "admin" role.</caption>
* const activeAdmins = query.get(['active', 'admin'], {
* index: 'activityAndRoles'
* }).run();
*
* @example <caption>Get all entities that match a certain weather condition.</caption>
* const niceDays = query.get(['sunny', 'humid', 'calm'], {
* index: 'weatherConditions'
* }).run();
*
* @method Query#get
* @param {array} keyList Key(s) defining the entity to retrieve. If
* `keyList` is not an array (i.e. for a single-value key), it will be
* wrapped in an array.
* @param {object} [opts] Configuration options.
* @param {string} [opts.string] Name of the secondary index to use in the
* query. If no index is specified, the main index is used.
* @returns {Query} A reference to itself for chaining.
* @since 3.0.0
*/
get (keyList = [], opts: any = {}) {
if (this.data) {
throw utils.err(`${DOMAIN}#get`)(500, INDEX_ERR)
}
if (keyList && !utils.isArray(keyList)) {
keyList = [keyList]
}
if (!keyList.length) {
this.getData()
return this
}
this.data = this.collection.getIndex(opts.index).get(keyList)
return this
}
/**
* Find the entity or entities that match the provided keyLists.
*
* @example <caption>Get the posts where "status" is "draft" or "inReview".</caption>
* const posts = query.getAll('draft', 'inReview', { index: 'status' }).run();
*
* @example <caption>Same as above.</caption>
* const posts = query.getAll(['draft'], ['inReview'], { index: 'status' }).run();
*
* @method Query#getAll
* @param {...Array} [keyList] Provide one or more keyLists, and all
* entities matching each keyList will be retrieved. If no keyLists are
* provided, all entities will be returned.
* @param {object} [opts] Configuration options.
* @param {string} [opts.index] Name of the secondary index to use in the
* query. If no index is specified, the main index is used.
* @returns {Query} A reference to itself for chaining.
* @since 3.0.0
*/
getAll(keyList?: [], opts?);
getAll (...args) {
let opts: any = {}
if (this.data) {
throw utils.err(`${DOMAIN}#getAll`)(500, INDEX_ERR)
}
if (!args.length || (args.length === 1 && utils.isObject(args[0]))) {
this.getData()
return this
} else if (args.length && utils.isObject(args[args.length - 1])) {
opts = args[args.length - 1]
args.pop()
}
const index = this.collection.getIndex(opts.index)
this.data = []
args.forEach(keyList => {
this.data = this.data.concat(index.get(keyList))
})
return this
}
/**
* Return the current data result of this query.
*
* @method Query#getData
* @returns {Array} The data in this query.
* @since 3.0.0
*/
getData () {
if (!this.data) {
this.data = this.collection.index.getAll()
}
return this.data
}
/**
* Implementation used by the `like` operator. Takes a pattern and flags and
* returns a `RegExp` instance that can test strings.
*
* @method Query#like
* @param {string} pattern Testing pattern.
* @param {string} flags Flags for the regular expression.
* @returns {RegExp} Regular expression for testing strings.
* @since 3.0.0
*/
like (pattern, flags) {
return new RegExp(
`^${escape(pattern)
.replace(percentRegExp, '.*')
.replace(underscoreRegExp, '.')}$`,
flags
)
}
/**
* Limit the result.
*
* @example <caption>Get only the first 2 posts.</caption>
* const store = new JSData.DataStore();
* store.defineMapper('post');
* const posts = [
* { author: 'John', age: 30, status: 'published', id: 1 },
* { author: 'Sally', age: 31, status: 'draft', id: 2 },
* { author: 'Mike', age: 32, status: 'draft', id: 3 },
* { author: 'Adam', age: 33, status: 'deleted', id: 4 },
* { author: 'Adam', age: 33, status: 'draft', id: 5 }
* ];
* store.add('post', posts);
* const results = store.query('post').limit(2).run();
* console.log(results);
*
* @method Query#limit
* @param {number} num The maximum number of entities to keep in the result.
* @returns {Query} A reference to itself for chaining.
* @since 3.0.0
*/
limit (num) {
if (!utils.isNumber(num)) {
throw utils.err(`${DOMAIN}#limit`, 'num')(400, 'number', num)
}
const data = this.getData()
this.data = data.slice(0, Math.min(data.length, num))
return this
}
/**
* Apply a mapping function to the result data.
*
* @example
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('user');
* const users = [
* { name: 'Peter', age: 25, id: 1 },
* { name: 'Jim', age: 19, id: 2 },
* { name: 'Mike', age: 17, id: 3 },
* { name: 'Alan', age: 29, id: 4 },
* { name: 'Katie', age: 33, id: 5 }
* ];
* store.add('user', users);
* const ages = store
* .query('user')
* .map(function (user) {
* return user.age;
* })
* .run();
* console.log(ages);
*
* @method Query#map
* @param {Function} mapFn Mapping function.
* @param {*} [thisArg] Context to which to bind `mapFn`.
* @returns {Query} A reference to itself for chaining.
* @since 3.0.0
*/
map (mapFn, thisArg?) {
this.data = this.getData().map(mapFn, thisArg)
return this
}
/**
* Return the result of calling the specified function on each item in this
* collection's main index.
*
* @example
* const stringAges = UserCollection.query().mapCall('toString').run();
*
* @method Query#mapCall
* @param {string} funcName Name of function to call
* @param args Remaining arguments to be passed to the function.
* @returns {Query} A reference to itself for chaining.
* @since 3.0.0
*/
mapCall (funcName, ...args) {
this.data = this.getData().map(item => item[funcName](...args))
return this
}
/**
* Complete the execution of the query and return the resulting data.
*
* @method Query#run
* @returns {Array} The result of executing this query.
* @since 3.0.0
*/
run () {
const data = this.data
this.data = null
return data
}
/**
* Skip a number of results.
*
* @example <caption>Get all but the first 2 posts.</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('post');
* const posts = [
* { author: 'John', age: 30, status: 'published', id: 1 },
* { author: 'Sally', age: 31, status: 'draft', id: 2 },
* { author: 'Mike', age: 32, status: 'draft', id: 3 },
* { author: 'Adam', age: 33, status: 'deleted', id: 4 },
* { author: 'Adam', age: 33, status: 'draft', id: 5 }
* ];
* store.add('post', posts);
* const results = store.query('post').skip(2).run();
* console.log(results);
*
* @method Query#skip
* @param {number} num The number of entities to skip.
* @returns {Query} A reference to itself for chaining.
* @since 3.0.0
*/
skip (num) {
if (!utils.isNumber(num)) {
throw utils.err(`${DOMAIN}#skip`, 'num')(400, 'number', num)
}
const data = this.getData()
if (num < data.length) {
this.data = data.slice(num)
} else {
this.data = []
}
return this
}
/**
* The filtering operators supported by {@link Query#filter}, and which are
* implemented by adapters (for the most part).
*
* @example <caption>Variant 1</caption>
* const JSData = require('js-data');
* const { DataStore } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const store = new DataStore();
* store.defineMapper('post');
* const posts = [
* { author: 'John', age: 30, status: 'published', id: 1 },
* { author: 'Sally', age: 31, status: 'published', id: 2 },
* { author: 'Mike', age: 32, status: 'published', id: 3 },
* { author: 'Adam', age: 33, status: 'deleted', id: 4 },
* { author: 'Adam', age: 33, status: 'published', id: 5 }
* ];
* store.add('post', posts);
* const publishedPosts = store.filter('post', {
* status: 'published',
* limit: 2