forked from 418sec/js-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollection.ts
982 lines (925 loc) · 29.4 KB
/
Collection.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
import utils from './utils'
import Component, { ComponentOpts } from './Component'
import Query from './Query'
import Record from './Record'
import Index from './mindex'
const { noValidatePath } = Record
const DOMAIN = 'Collection'
export interface CollectionOpts extends ComponentOpts {
/**
* Whether to call {@link Record#commit} on records that are added to the
* collection and already exist in the collection.
*
* @name Collection#commitOnMerge
* @type {boolean}
* @default true
*/
commitOnMerge?: boolean
/**
* Whether record events should bubble up and be emitted by the collection.
*
* @name Collection#emitRecordEvents
* @type {boolean}
* @default true
*/
emitRecordEvents?: boolean
/**
* Field to be used as the unique identifier for records in this collection.
* Defaults to `"id"` unless {@link Collection#mapper} is set, in which case
* this will default to {@link Mapper#idAttribute}.
*
* @name Collection#idAttribute
* @type {string}
* @default "id"
*/
idAttribute?: string
/**
* What to do when inserting a record into this Collection that shares a
* primary key with a record already in this Collection.
*
* Possible values:
* merge
* replace
* skip
*
* Merge:
*
* Recursively shallow copy properties from the new record onto the existing
* record.
*
* Replace:
*
* Shallow copy top-level properties from the new record onto the existing
* record. Any top-level own properties of the existing record that are _not_
* on the new record will be removed.
*
* Skip:
*
* Ignore new record, keep existing record.
*
* @default "merge"
*/
onConflict?: 'merge' | 'replace' | 'skip'
}
const COLLECTION_DEFAULTS: CollectionOpts = {
commitOnMerge: true,
emitRecordEvents: true,
idAttribute: 'id',
onConflict: 'merge'
}
/**
* An ordered set of {@link Record} instances.
*
* @example <caption>Collection#constructor</caption>
* // import { Collection, Record } from 'js-data';
* const JSData = require('js-data');
* const {Collection, Record} = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const user1 = new Record({ id: 1 });
* const user2 = new Record({ id: 2 });
* const UserCollection = new Collection([user1, user2]);
* console.log(UserCollection.get(1) === user1);
*
* @class Collection
* @extends Component
* @param {array} [records] Initial set of records to insert into the
* collection.
* @param {object} [opts] Configuration options.
* @param {string} [opts.commitOnMerge] See {@link Collection#commitOnMerge}.
* @param {string} [opts.idAttribute] See {@link Collection#idAttribute}.
* @param {string} [opts.onConflict="merge"] See {@link Collection#onConflict}.
* @param {string} [opts.mapper] See {@link Collection#mapper}.
* @since 3.0.0
*/
export default class Collection extends Component {
queryClass
emitRecordEvents: any
onConflict: string
/**
* Default Mapper for this collection. Optional. If a Mapper is provided, then
* the collection will use the {@link Mapper#idAttribute} setting, and will
* wrap records in {@link Mapper#recordClass}.
*
* @example <caption>Collection#mapper</caption>
* const JSData = require('js-data');
* const {Collection, Mapper} = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* class MyMapperClass extends Mapper {
* foo () { return 'bar'; }
* }
* const myMapper = new MyMapperClass({ name: 'myMapper' });
* const collection = new Collection(null, { mapper: myMapper });
*
* @name Collection#mapper
* @type {Mapper}
* @default null
* @since 3.0.0
*/
mapper: any
/**
* The main index, which uses @{link Collection#recordId} as the key.
*
* @name Collection#index
* @type {Index}
*/
index: Index
/**
* Object that holds the secondary indexes of this collection.
*
* @name Collection#indexes
* @type {Object.<string, Index>}
*/
indexes: { [key: string]: Index } = {}
idAttribute: any
_added = {}
emit: any
constructor (records: any = {}, opts: CollectionOpts | string | any = {}) {
super(opts)
if (records && !utils.isArray(records)) {
opts = records
records = []
}
if (utils.isString(opts)) {
opts = { idAttribute: opts }
}
// Apply user-provided configuration
utils.fillIn(this, opts)
// Fill in any missing options with the defaults
utils.fillIn(this, utils.copy(COLLECTION_DEFAULTS))
if (!this.queryClass) {
this.queryClass = Query
}
const idAttribute = this.recordId()
this.index = new Index([idAttribute], {
hashCode (obj) {
return utils.get(obj, idAttribute)
}
})
// Insert initial data into the collection
if (utils.isObject(records) || (utils.isArray(records) && records.length)) {
this.add(records)
}
}
/**
* Used to bind to events emitted by records in this Collection.
*
* @method Collection#_onRecordEvent
* @since 3.0.0
* @private
* @param {...*} [args] Args passed to {@link Collection#emit}.
*/
_onRecordEvent (...args) {
if (this.emitRecordEvents) {
this.emit(...args)
}
}
/**
* Insert the provided record or records.
*
* If a record is already in the collection then the provided record will
* either merge with or replace the existing record based on the value of the
* `onConflict` option.
*
* The collection's secondary indexes will be updated as each record is
* visited.
*
* @method Collection#add
* @since 3.0.0
* @param {(Object|Object[]|Record|Record[])} records The record or records to insert.
* @param {object} [opts] Configuration options.
* @param {boolean} [opts.commitOnMerge=true] See {@link Collection#commitOnMerge}.
* @param {boolean} [opts.noValidate] See {@link Record#noValidate}.
* @param {string} [opts.onConflict] See {@link Collection#onConflict}.
* @returns {(Object|Object[]|Record|Record[])} The added record or records.
*/
add (records, opts: any = {}) {
// Fill in "opts" with the Collection's configuration
utils._(opts, this)
records = this.beforeAdd(records, opts) || records
// Track whether just one record or an array of records is being inserted
let singular = false
const idAttribute = this.recordId()
if (!utils.isArray(records)) {
if (utils.isObject(records)) {
records = [records]
singular = true
} else {
throw utils.err(`${DOMAIN}#add`, 'records')(
400,
'object or array',
records
)
}
}
// Map the provided records to existing records.
// New records will be inserted. If any records map to existing records,
// they will be merged into the existing records according to the onConflict
// option.
records = records.map(record => {
const id = this.recordId(record)
// Grab existing record if there is one
const existing = id === undefined ? id : this.get(id)
// If the currently visited record is just a reference to an existing
// record, then there is nothing to be done. Exit early.
if (record === existing) {
return existing
}
if (existing) {
// Here, the currently visited record corresponds to a record already
// in the collection, so we need to merge them
const onConflict = opts.onConflict || this.onConflict
if (
onConflict !== 'merge' &&
onConflict !== 'replace' &&
onConflict !== 'skip'
) {
throw utils.err(`${DOMAIN}#add`, 'opts.onConflict')(
400,
'one of (merge, replace, skip)',
onConflict,
true
)
}
const existingNoValidate = existing._get(noValidatePath)
if (opts.noValidate) {
// Disable validation
existing._set(noValidatePath, true)
}
if (onConflict === 'merge') {
utils.deepMixIn(existing, record)
} else if (onConflict === 'replace') {
utils.forOwn(existing, (value, key) => {
if (key !== idAttribute && record[key] === undefined) {
existing[key] = undefined
}
})
existing.set(record)
} // else if(onConflict === 'skip'){ do nothing }
if (opts.noValidate) {
// Restore previous `noValidate` value
existing._set(noValidatePath, existingNoValidate)
}
record = existing
if (opts.commitOnMerge && utils.isFunction(record.commit)) {
record.commit()
}
// Update all indexes in the collection
this.updateIndexes(record)
} else {
// Here, the currently visited record does not correspond to any record
// in the collection, so (optionally) instantiate this record and insert
// it into the collection
record = this.mapper ? this.mapper.createRecord(record, opts) : record
this.index.insertRecord(record)
utils.forOwn(this.indexes, (index, name) => {
index.insertRecord(record)
})
if (record && utils.isFunction(record.on)) {
record.on('all', this._onRecordEvent, this)
}
}
return record
})
// Finally, return the inserted data
const result = singular ? records[0] : records
if (!opts.silent) {
this.emit('add', result)
}
return this.afterAdd(records, opts, result) || result
}
/**
* Lifecycle hook called by {@link Collection#add}. If this method returns a
* value then {@link Collection#add} will return that same value.
*
* @method Collection#method
* @since 3.0.0
* @param {(Object|Object[]|Record|Record[])} record The record or records
* that were added to this Collection by {@link Collection#add}.
* @param {object} opts The `opts` argument passed to {@link Collection#add}.
* @param result
*/
afterAdd (record, opts, result) {
return null
}
/**
* Lifecycle hook called by {@link Collection#remove}. If this method returns
* a value then {@link Collection#remove} will return that same value.
*
* @method Collection#afterRemove
* @since 3.0.0
* @param {(string|number)} id The `id` argument passed to {@link Collection#remove}.
* @param {object} opts The `opts` argument passed to {@link Collection#remove}.
* @param {object} record The result that will be returned by {@link Collection#remove}.
*/
afterRemove (id, opts, record) {
return null
}
/**
* Lifecycle hook called by {@link Collection#removeAll}. If this method
* returns a value then {@link Collection#removeAll} will return that same
* value.
*
* @method Collection#afterRemoveAll
* @since 3.0.0
* @param {object} query The `query` argument passed to {@link Collection#removeAll}.
* @param {object} opts The `opts` argument passed to {@link Collection#removeAll}.
* @param {object} records The result that will be returned by {@link Collection#removeAll}.
*/
afterRemoveAll (query, opts, records) {
return null
}
/**
* Lifecycle hook called by {@link Collection#add}. If this method returns a
* value then the `records` argument in {@link Collection#add} will be
* re-assigned to the returned value.
*
* @method Collection#beforeAdd
* @since 3.0.0
* @param {(Object|Object[]|Record|Record[])} records The `records` argument passed to {@link Collection#add}.
* @param {object} opts The `opts` argument passed to {@link Collection#add}.
*/
beforeAdd (records, opts) {
return null
}
/**
* Lifecycle hook called by {@link Collection#remove}.
*
* @method Collection#beforeRemove
* @since 3.0.0
* @param {(string|number)} id The `id` argument passed to {@link Collection#remove}.
* @param {object} opts The `opts` argument passed to {@link Collection#remove}.
*/
beforeRemove (id, opts) {
return null
}
/**
* Lifecycle hook called by {@link Collection#removeAll}.
*
* @method Collection#beforeRemoveAll
* @since 3.0.0
* @param {object} query The `query` argument passed to {@link Collection#removeAll}.
* @param {object} opts The `opts` argument passed to {@link Collection#removeAll}.
*/
beforeRemoveAll (query, opts) {
return null
}
/**
* Find all records between two boundaries.
*
* Shortcut for `collection.query().between(18, 30, { index: 'age' }).run()`
*
* @example
* // Get all users ages 18 to 30
* const users = collection.between(18, 30, { index: 'age' });
*
* @example
* // Same as above
* const users = collection.between([18], [30], { index: 'age' });
*
* @method Collection#between
* @since 3.0.0
* @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 records
* on the left boundary.
* @param {boolean} [opts.rightInclusive=false] Whether to include records
* on the left boundary.
* @param {boolean} [opts.limit] Limit the result to a certain number.
* @param {boolean} [opts.offset] The number of resulting records to skip.
* @returns {Object[]|Record[]} The result.
*/
between (leftKeys, rightKeys, opts) {
return this.query()
.between(leftKeys, rightKeys, opts)
.run()
}
/**
* Create a new secondary index on the contents of the collection.
*
* @example
* // Index users by age
* collection.createIndex('age');
*
* @example
* // Index users by status and role
* collection.createIndex('statusAndRole', ['status', 'role']);
*
* @method Collection#createIndex
* @since 3.0.0
* @param {string} name The name of the new secondary index.
* @param {string[]} [fieldList] Array of field names to use as the key or
* compound key of the new secondary index. If no fieldList is provided, then
* the name will also be the field that is used to index the collection.
* @param opts
*/
createIndex (name, fieldList?, opts: any = {}) {
if (utils.isString(name) && fieldList === undefined) {
fieldList = [name]
}
opts.hashCode = opts.hashCode || (obj => this.recordId(obj))
const index = (this.indexes[name] = new Index(fieldList, opts))
this.index.visitAll(index.insertRecord, index)
}
/**
* Find the record or records that match the provided query or pass the
* provided filter function.
*
* Shortcut for `collection.query().filter(queryOrFn[, thisArg]).run()`
*
* @example <caption>Collection#filter</caption>
* const JSData = require('js-data');
* const { Collection } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const collection = new Collection([
* { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() }
* ]);
*
* // Get the draft posts created less than three months ago
* let posts = collection.filter({
* where: {
* status: {
* '==': 'draft'
* },
* created_at_timestamp: {
* '>=': (new Date().getTime() - (1000 \* 60 \* 60 \* 24 \* 30 \* 3)) // 3 months ago
* }
* }
* });
* console.log(posts);
*
* // Use a custom filter function
* posts = collection.filter((post) => post.id % 2 === 0);
*
* @method Collection#filter
* @param {(Object|Function)} [queryOrFn={}] Selection query or filter
* function.
* @param {object} [thisArg] Context to which to bind `queryOrFn` if
* `queryOrFn` is a function.
* @returns {Array} The result.
* @see query
* @since 3.0.0
*/
filter (queryOrFn, thisArg?) {
return this.query()
.filter(queryOrFn, thisArg)
.run()
}
/**
* Iterate over all records.
*
* @example
* collection.forEach(function (record) {
* // do something
* });
*
* @method Collection#forEach
* @since 3.0.0
* @param {Function} forEachFn Iteration function.
* @param {*} [thisArg] Context to which to bind `forEachFn`.
* @returns {Array} The result.
*/
forEach (forEachFn, thisArg?) {
this.index.visitAll(forEachFn, thisArg)
}
/**
* Get the record with the given id.
*
* @method Collection#get
* @since 3.0.0
* @param {(string|number)} id The primary key of the record to get.
* @returns {(Object|Record)} The record with the given id.
*/
get (id) {
const instances =
id === undefined
? []
: this.query()
.get(id)
.run()
return instances.length ? instances[0] : undefined
}
/**
* Find the record or records that match the provided keyLists.
*
* Shortcut for `collection.query().getAll(keyList1, keyList2, ...).run()`
*
* @example
* // Get the posts where "status" is "draft" or "inReview"
* const posts = collection.getAll('draft', 'inReview', { index: 'status' });
*
* @example
* // Same as above
* const posts = collection.getAll(['draft'], ['inReview'], { index: 'status' });
*
* @method Collection#getAll
* @since 3.0.0
* @param {...Array} [keyList] Provide one or more keyLists, and all
* records matching each keyList will be retrieved. If no keyLists are
* provided, all records 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 {Array} The result.
*/
getAll(keyList?: Array<string | number> | string | number, opts?)
getAll(keyList?: Array<string | number> | string | number, ...args)
getAll (...args) {
return this.query()
.getAll(...args)
.run()
}
/**
* Return the index with the given name. If no name is provided, return the
* main index. Throws an error if the specified index does not exist.
*
* @method Collection#getIndex
* @since 3.0.0
* @param {string} [name] The name of the index to retrieve.
*/
getIndex (name): Index {
const index = name ? this.indexes[name] : this.index
if (!index) {
throw utils.err(`${DOMAIN}#getIndex`, name)(404, 'index')
}
return index
}
/**
* Limit the result.
*
* Shortcut for `collection.query().limit(maximumNumber).run()`
*
* @example
* const posts = collection.limit(10);
*
* @method Collection#limit
* @since 3.0.0
* @param {number} num The maximum number of records to keep in the result.
* @returns {Array} The result.
*/
limit (num) {
return this.query()
.limit(num)
.run()
}
/**
* Apply a mapping function to all records.
*
* @example
* const names = collection.map((user) => user.name);
*
* @method Collection#map
* @since 3.0.0
* @param {Function} mapFn Mapping function.
* @param {*} [thisArg] Context to which to bind `mapFn`.
* @returns {Array} The result of the mapping.
*/
map (cb, thisArg) {
const data = []
this.index.visitAll(value => {
data.push(cb.call(thisArg, value))
})
return data
}
/**
* Return the result of calling the specified function on each record in this
* collection's main index.
*
* @method Collection#mapCall
* @since 3.0.0
* @param {string} funcName Name of function to call
* @param {...*} [args] Remaining arguments to be passed to the function.
* @returns {Array} The result.
*/
mapCall (funcName, ...args) {
const data = []
this.index.visitAll(record => {
data.push(record[funcName](...args))
})
return data
}
/**
* Return all "unsaved" (not uniquely identifiable) records in this colleciton.
*
* @method Collection#prune
* @param {object} [opts] Configuration options, passed to {@link Collection#removeAll}.
* @since 3.0.0
* @returns {Array} The removed records, if any.
*/
prune (opts) {
return this.removeAll(this.unsaved(), opts)
}
/**
* Create a new query to be executed against the contents of the collection.
* The result will be all or a subset of the contents of the collection.
*
* @example
* // Grab page 2 of users between ages 18 and 30
* collection.query()
* .between(18, 30, { index: 'age' }) // between ages 18 and 30
* .skip(10) // second page
* .limit(10) // page size
* .run();
*
* @method Collection#query
* @since 3.0.0
* @returns {Query} New query object.
*/
query (): Query {
const Ctor = this.queryClass
return new Ctor(this)
}
/**
* Return the primary key of the given, or if no record is provided, return the
* name of the field that holds the primary key of records in this Collection.
*
* @method Collection#recordId
* @since 3.0.0
* @param {(Object|Record)} [record] The record whose primary key is to be
* returned.
* @returns {(string|number)} Primary key or name of field that holds primary
* key.
*/
recordId (record?) {
if (record) {
return utils.get(record, this.recordId())
}
return this.mapper ? this.mapper.idAttribute : this.idAttribute
}
/**
* Reduce the data in the collection to a single value and return the result.
*
* @example
* const totalVotes = collection.reduce((prev, record) => {
* return prev + record.upVotes + record.downVotes;
* }, 0);
*
* @method Collection#reduce
* @since 3.0.0
* @param {Function} cb Reduction callback.
* @param {*} initialValue Initial value of the reduction.
* @returns {*} The result.
*/
reduce (cb, initialValue) {
const data = this.getAll()
return data.reduce(cb, initialValue)
}
/**
* Remove the record with the given id from this Collection.
*
* @method Collection#remove
* @since 3.0.0
* @param {(string|number|object|Record)} idOrRecord The primary key of the
* record to be removed, or a reference to the record that is to be removed.
* @param {object} [opts] Configuration options.
* @returns {Object|Record} The removed record, if any.
*/
remove (idOrRecord, opts: any = {}) {
this.beforeRemove(idOrRecord, opts)
let record = utils.isSorN(idOrRecord) ? this.get(idOrRecord) : idOrRecord
// The record is in the collection, remove it
if (utils.isObject(record)) {
record = this.index.removeRecord(record)
if (record) {
utils.forOwn(this.indexes, (index, name) => {
index.removeRecord(record)
})
if (utils.isFunction(record.off)) {
record.off('all', this._onRecordEvent, this)
}
if (!opts.silent) {
this.emit('remove', record)
}
}
}
return this.afterRemove(idOrRecord, opts, record) || record
}
/**
* Remove from this collection the given records or the records selected by
* the given "query".
*
* @method Collection#removeAll
* @since 3.0.0
* @param {Object|Object[]|Record[]} [queryOrRecords={}] Records to be removed or selection query. See {@link query}.
* @param {object} [queryOrRecords.where] See {@link query.where}.
* @param {number} [queryOrRecords.offset] See {@link query.offset}.
* @param {number} [queryOrRecords.limit] See {@link query.limit}.
* @param {string|Array[]} [queryOrRecords.orderBy] See {@link query.orderBy}.
* @param {object} [opts] Configuration options.
* @returns {(Object[]|Record[])} The removed records, if any.
*/
removeAll (queryOrRecords, opts: any = {}) {
this.beforeRemoveAll(queryOrRecords, opts)
let records = utils.isArray(queryOrRecords)
? queryOrRecords.slice()
: this.filter(queryOrRecords)
// Remove each selected record from the collection
const optsCopy = utils.plainCopy(opts)
optsCopy.silent = true
records = records
.map(record => this.remove(record, optsCopy))
.filter(record => record)
if (!opts.silent) {
this.emit('remove', records)
}
return this.afterRemoveAll(queryOrRecords, opts, records) || records
}
/**
* Skip a number of results.
*
* Shortcut for `collection.query().skip(numberToSkip).run()`
*
* @example
* const posts = collection.skip(10);
*
* @method Collection#skip
* @since 3.0.0
* @param {number} num The number of records to skip.
* @returns {Array} The result.
*/
skip (num) {
return this.query()
.skip(num)
.run()
}
/**
* Return the plain JSON representation of all items in this collection.
* Assumes records in this collection have a toJSON method.
*
* @method Collection#toJSON
* @since 3.0.0
* @param {object} [opts] Configuration options.
* @param {string[]} [opts.with] Array of relation names or relation fields
* to include in the representation.
* @returns {Array} The records.
*/
toJSON (opts?) {
return this.mapCall('toJSON', opts)
}
/**
* Return all "unsaved" (not uniquely identifiable) records in this colleciton.
*
* @method Collection#unsaved
* @since 3.0.0
* @returns {Array} The unsaved records, if any.
*/
unsaved (opts?) {
return this.index.get()
}
/**
* Update a record's position in a single index of this collection. See
* {@link Collection#updateIndexes} to update a record's position in all
* indexes at once.
*
* @method Collection#updateIndex
* @since 3.0.0
* @param {object} record The record to update.
* @param {object} [opts] Configuration options.
* @param {string} [opts.index] The index in which to update the record's
* position. If you don't specify an index then the record will be updated
* in the main index.
*/
updateIndex (record, opts: { index?: string } = {}) {
this.getIndex(opts.index).updateRecord(record)
}
/**
* Updates all indexes in this collection for the provided record. Has no
* effect if the record is not in the collection.
*
* @method Collection#updateIndexes
* @since 3.0.0
* @param {object} record TODO
*/
updateIndexes (record) {
this.index.updateRecord(record)
utils.forOwn(this.indexes, index => index.updateRecord(record))
}
}
/**
* Fired when a record changes. Only works for records that have tracked changes.
* See {@link Collection~changeListener} on how to listen for this event.
*
* @event Collection#change
* @see Collection~changeListener
*/
/**
* Callback signature for the {@link Collection#event:change} event.
*
* @example
* function onChange (record, changes) {
* // do something
* }
* collection.on('change', onChange);
*
* @callback Collection~changeListener
* @param {Record} The Record that changed.
* @param {object} The changes.
* @see Collection#event:change
* @since 3.0.0
*/
/**
* Fired when one or more records are added to the Collection. See
* {@link Collection~addListener} on how to listen for this event.
*
* @event Collection#add
* @see Collection~addListener
* @see Collection#event:add
* @see Collection#add
*/
/**
* Callback signature for the {@link Collection#event:add} event.
*
* @example
* function onAdd (recordOrRecords) {
* // do something
* }
* collection.on('add', onAdd);
*
* @callback Collection~addListener
* @param {Record|Record[]} The Record or Records that were added.
* @see Collection#event:add
* @see Collection#add
* @since 3.0.0
*/
/**
* Fired when one or more records are removed from the Collection. See
* {@link Collection~removeListener} for how to listen for this event.
*
* @event Collection#remove
* @see Collection~removeListener
* @see Collection#event:remove
* @see Collection#remove
* @see Collection#removeAll
*/
/**
* Callback signature for the {@link Collection#event:remove} event.
*
* @example
* function onRemove (recordsOrRecords) {
* // do something
* }
* collection.on('remove', onRemove);
*
* @callback Collection~removeListener
* @param {Record|Record[]} Record or Records that were removed.
* @see Collection#event:remove
* @see Collection#remove
* @see Collection#removeAll
* @since 3.0.0
*/
/**
* Create a subclass of this Collection:
* @example <caption>Collection.extend</caption>
* const JSData = require('js-data');
* const { Collection } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* // Extend the class using ES2015 class syntax.
* class CustomCollectionClass extends Collection {
* foo () { return 'bar'; }
* static beep () { return 'boop'; }
* }
* const customCollection = new CustomCollectionClass();
* console.log(customCollection.foo());
* console.log(CustomCollectionClass.beep());
*
* // Extend the class using alternate method.
* const OtherCollectionClass = Collection.extend({
* foo () { return 'bar'; }
* }, {
* beep () { return 'boop'; }
* });
* const otherCollection = new OtherCollectionClass();
* console.log(otherCollection.foo());
* console.log(OtherCollectionClass.beep());
*
* // Extend the class, providing a custom constructor.
* function AnotherCollectionClass () {
* Collection.call(this);
* this.created_at = new Date().getTime();
* }
* Collection.extend({
* constructor: AnotherCollectionClass,
* foo () { return 'bar'; }
* }, {
* beep () { return 'boop'; }
* });
* const anotherCollection = new AnotherCollectionClass();
* console.log(anotherCollection.created_at);
* console.log(anotherCollection.foo());
* console.log(AnotherCollectionClass.beep());
*
* @method Collection.extend
* @param {object} [props={}] Properties to add to the prototype of the
* subclass.
* @param {object} [props.constructor] Provide a custom constructor function
* to be used as the subclass itself.
* @param {object} [classProps={}] Static properties to add to the subclass.
* @returns {Constructor} Subclass of this Collection class.
* @since 3.0.0
*/