-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
identifier-array.ts
1027 lines (890 loc) · 31.2 KB
/
identifier-array.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
/**
@module @ember-data/store
*/
// @ts-expect-error
import { tagForProperty } from '@ember/-internals/metal';
import { assert, deprecate } from '@ember/debug';
import { get, set } from '@ember/object';
import { dependentKeyCompat } from '@ember/object/compat';
// eslint-disable-next-line no-restricted-imports
import { compare } from '@ember/utils';
import { tracked } from '@glimmer/tracking';
// @ts-expect-error
import { dirtyTag } from '@glimmer/validator';
import Ember from 'ember';
import {
DEPRECATE_A_USAGE,
DEPRECATE_ARRAY_LIKE,
DEPRECATE_COMPUTED_CHAINS,
DEPRECATE_PROMISE_PROXIES,
DEPRECATE_SNAPSHOT_MODEL_CLASS_ACCESS,
} from '@ember-data/deprecations';
import { DEBUG } from '@ember-data/env';
import { ImmutableRequestInfo } from '@ember-data/request/-private/types';
import { addToTransaction, subscribe } from '@ember-data/tracking/-private';
import { Links, PaginationLinks } from '@ember-data/types/q/ember-data-json-api';
import type { StableRecordIdentifier } from '@ember-data/types/q/identifier';
import type { RecordInstance } from '@ember-data/types/q/record-instance';
import { Dict } from '@ember-data/types/q/utils';
import { recordIdentifierFor } from '../caches/instance-cache';
import type RecordArrayManager from '../managers/record-array-manager';
import { PromiseArray, promiseArray } from '../proxies/promise-proxies';
import type Store from '../store-service';
type KeyType = string | symbol | number;
const ARRAY_GETTER_METHODS = new Set<KeyType>([
Symbol.iterator,
'concat',
'entries',
'every',
'fill',
'filter',
'find',
'findIndex',
'flat',
'flatMap',
'forEach',
'includes',
'indexOf',
'join',
'keys',
'lastIndexOf',
'map',
'reduce',
'reduceRight',
'slice',
'some',
'values',
]);
const ARRAY_SETTER_METHODS = new Set<KeyType>(['push', 'pop', 'unshift', 'shift', 'splice', 'sort']);
const SYNC_PROPS = new Set<KeyType>(['[]', 'length', 'links', 'meta']);
function isArrayGetter(prop: KeyType): boolean {
return ARRAY_GETTER_METHODS.has(prop);
}
function isArraySetter(prop: KeyType): boolean {
return ARRAY_SETTER_METHODS.has(prop);
}
export const IDENTIFIER_ARRAY_TAG = Symbol('#tag');
export const SOURCE = Symbol('#source');
export const MUTATE = Symbol('#update');
export const NOTIFY = Symbol('#notify');
const IS_COLLECTION = Symbol.for('Collection');
export function notifyArray(arr: IdentifierArray) {
addToTransaction(arr[IDENTIFIER_ARRAY_TAG]);
if (DEPRECATE_COMPUTED_CHAINS) {
// eslint-disable-next-line
dirtyTag(tagForProperty(arr, 'length'));
// eslint-disable-next-line
dirtyTag(tagForProperty(arr, '[]'));
}
}
function convertToInt(prop: KeyType): number | null {
if (typeof prop === 'symbol') return null;
const num = Number(prop);
if (isNaN(num)) return null;
return num % 1 === 0 ? num : null;
}
class Tag {
@tracked ref = null;
declare shouldReset: boolean;
/*
* whether this was part of a transaction when last mutated
*/
declare t: boolean;
declare _debug_base: string;
declare _debug_prop: string;
constructor() {
if (DEBUG) {
const [arr, prop] = arguments as unknown as [IdentifierArray, string];
this._debug_base = arr.constructor.name + ':' + String(arr.modelName);
this._debug_prop = prop;
}
this.shouldReset = false;
this.t = false;
}
}
type ProxiedMethod = (...args: unknown[]) => unknown;
declare global {
interface ProxyConstructor {
new <TSource extends object, TTarget extends object>(target: TSource, handler: ProxyHandler<TSource>): TTarget;
}
}
export type IdentifierArrayCreateOptions = {
identifiers: StableRecordIdentifier[];
type?: string;
store: Store;
allowMutation: boolean;
manager: RecordArrayManager;
links?: Links | PaginationLinks | null;
meta?: Dict<unknown> | null;
};
function deprecateArrayLike(className: string, fnName: string, replName: string) {
deprecate(
`The \`${fnName}\` method on the class ${className} is deprecated. Use the native array method \`${replName}\` instead.`,
false,
{
id: 'ember-data:deprecate-array-like',
until: '5.0',
since: { enabled: '4.7', available: '4.7' },
for: 'ember-data',
}
);
}
interface PrivateState {
links: Links | PaginationLinks | null;
meta: Dict<unknown> | null;
}
type ForEachCB = (record: RecordInstance, index: number, context: IdentifierArray) => void;
function safeForEach(
instance: IdentifierArray,
arr: StableRecordIdentifier[],
store: Store,
callback: ForEachCB,
target: unknown
) {
if (target === undefined) {
target = null;
}
// clone to prevent mutation
arr = arr.slice();
assert('`forEach` expects a function as first argument.', typeof callback === 'function');
// because we retrieveLatest above we need not worry if array is mutated during iteration
// by unloadRecord/rollbackAttributes
// push/add/removeObject may still be problematic
// but this is a more traditionally expected forEach bug.
const length = arr.length; // we need to access length to ensure we are consumed
for (let index = 0; index < length; index++) {
callback.call(target, store._instanceCache.getRecord(arr[index]), index, instance);
}
return instance;
}
/**
A record array is an array that contains records of a certain type (or modelName).
The record array materializes records as needed when they are retrieved for the first
time. You should not create record arrays yourself. Instead, an instance of
`RecordArray` or its subclasses will be returned by your application's store
in response to queries.
This class should not be imported and instantiated by consuming applications.
@class RecordArray
@public
*/
interface IdentifierArray extends Omit<Array<RecordInstance>, '[]'> {
[MUTATE]?(prop: string, args: unknown[], result?: unknown): void;
}
class IdentifierArray {
declare DEPRECATED_CLASS_NAME: string;
/**
The flag to signal a `RecordArray` is currently loading data.
Example
```javascript
let people = store.peekAll('person');
people.isUpdating; // false
people.update();
people.isUpdating; // true
```
@property isUpdating
@public
@type Boolean
*/
@tracked isUpdating: boolean = false;
isLoaded: boolean = true;
isDestroying: boolean = false;
isDestroyed: boolean = false;
_updatingPromise: PromiseArray<RecordInstance, IdentifierArray> | Promise<IdentifierArray> | null = null;
[IS_COLLECTION] = true;
declare [IDENTIFIER_ARRAY_TAG]: Tag;
[SOURCE]: StableRecordIdentifier[];
[NOTIFY]() {
notifyArray(this);
}
declare links: Links | PaginationLinks | null;
declare meta: Dict<unknown> | null;
/**
The modelClass represented by this record array.
@property type
@public
@deprecated
@type {subclass of Model}
*/
declare modelName?: string;
/**
The store that created this record array.
@property store
@private
@type Store
*/
declare store: Store;
declare _manager: RecordArrayManager;
destroy(clear: boolean) {
this.isDestroying = !clear;
// changing the reference breaks the Proxy
// this[SOURCE] = [];
this[SOURCE].length = 0;
this[NOTIFY]();
this.isDestroyed = !clear;
}
// length must be on self for proxied methods to work properly
@dependentKeyCompat
get length() {
return this[SOURCE].length;
}
set length(value) {
this[SOURCE].length = value;
}
// here to support computed chains
// and {{#each}}
get '[]'() {
if (DEPRECATE_COMPUTED_CHAINS) {
return this;
}
}
constructor(options: IdentifierArrayCreateOptions) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let self = this;
this.modelName = options.type;
this.store = options.store;
this._manager = options.manager;
this[SOURCE] = options.identifiers;
// @ts-expect-error
this[IDENTIFIER_ARRAY_TAG] = DEBUG ? new Tag(this, 'length') : new Tag();
const store = options.store;
const boundFns = new Map<KeyType, ProxiedMethod>();
const _TAG = this[IDENTIFIER_ARRAY_TAG];
const PrivateState: PrivateState = {
links: options.links || null,
meta: options.meta || null,
};
let transaction: boolean = false;
// when a mutation occurs
// we track all mutations within the call
// and forward them as one
const proxy = new Proxy<StableRecordIdentifier[], RecordInstance[]>(this[SOURCE], {
get(target: StableRecordIdentifier[], prop: KeyType, receiver: IdentifierArray): unknown {
let index = convertToInt(prop);
if (_TAG.shouldReset && (index !== null || SYNC_PROPS.has(prop) || isArrayGetter(prop))) {
options.manager._syncArray(receiver as unknown as IdentifierArray);
_TAG.t = false;
_TAG.shouldReset = false;
}
if (index !== null) {
const identifier = target[index];
if (!transaction) {
subscribe(_TAG);
}
return identifier && store._instanceCache.getRecord(identifier);
}
if (prop === 'meta') return subscribe(_TAG), PrivateState.meta;
if (prop === 'links') return subscribe(_TAG), PrivateState.links;
if (prop === '[]') return subscribe(_TAG), receiver;
if (isArrayGetter(prop)) {
let fn = boundFns.get(prop);
if (fn === undefined) {
if (prop === 'forEach') {
fn = function () {
subscribe(_TAG);
transaction = true;
let result = safeForEach(receiver, target, store, arguments[0] as ForEachCB, arguments[1]);
transaction = false;
return result;
};
} else {
fn = function () {
subscribe(_TAG);
// array functions must run through Reflect to work properly
// binding via other means will not work.
transaction = true;
let result = Reflect.apply(target[prop] as ProxiedMethod, receiver, arguments) as unknown;
transaction = false;
return result;
};
}
boundFns.set(prop, fn);
}
return fn;
}
if (isArraySetter(prop)) {
let fn = boundFns.get(prop);
if (fn === undefined) {
fn = function () {
// array functions must run through Reflect to work properly
// binding via other means will not work.
if (!options.allowMutation) {
assert(`Mutating this array of records via ${String(prop)} is not allowed.`, options.allowMutation);
return;
}
const args: unknown[] = Array.prototype.slice.call(arguments);
assert(`Cannot start a new array transaction while a previous transaction is underway`, !transaction);
transaction = true;
let result: unknown = Reflect.apply(target[prop] as ProxiedMethod, receiver, args);
self[MUTATE]!(prop as string, args, result);
addToTransaction(_TAG);
// TODO handle cache updates
transaction = false;
return result;
};
boundFns.set(prop, fn);
}
return fn;
}
if (prop in self) {
if (DEPRECATE_ARRAY_LIKE) {
if (prop === 'firstObject') {
deprecateArrayLike(self.DEPRECATED_CLASS_NAME, prop, '[0]');
return receiver[0];
} else if (prop === 'lastObject') {
deprecateArrayLike(self.DEPRECATED_CLASS_NAME, prop, 'at(-1)');
return receiver[receiver.length - 1];
}
}
if (prop === NOTIFY || prop === IDENTIFIER_ARRAY_TAG || prop === SOURCE) {
return self[prop];
}
let fn = boundFns.get(prop);
if (fn) return fn;
let outcome: unknown = self[prop];
if (typeof outcome === 'function') {
fn = function () {
subscribe(_TAG);
// array functions must run through Reflect to work properly
// binding via other means will not work.
return Reflect.apply(outcome as ProxiedMethod, receiver, arguments) as unknown;
};
boundFns.set(prop, fn);
return fn;
}
return subscribe(_TAG), outcome;
}
return target[prop];
},
set(target: StableRecordIdentifier[], prop: KeyType, value: unknown /*, receiver */): boolean {
if (prop === 'length') {
if (!transaction && value === 0) {
transaction = true;
addToTransaction(_TAG);
Reflect.set(target, prop, value);
self[MUTATE]!('length 0', []);
transaction = false;
return true;
} else if (transaction) {
return Reflect.set(target, prop, value);
} else {
assert(`unexpected length set`);
}
}
if (prop === 'links') {
PrivateState.links = (value || null) as PaginationLinks | Links | null;
return true;
}
if (prop === 'meta') {
PrivateState.meta = (value || null) as Dict<unknown> | null;
return true;
}
let index = convertToInt(prop);
if (index === null || index > target.length) {
if (prop in self) {
self[prop] = value;
return true;
}
return false;
}
if (!options.allowMutation) {
assert(`Mutating ${String(prop)} on this RecordArray is not allowed.`, options.allowMutation);
return false;
}
let original: StableRecordIdentifier | undefined = target[index];
let newIdentifier = extractIdentifierFromRecord(value as RecordInstance);
(target as unknown as Record<KeyType, unknown>)[index] = newIdentifier;
if (!transaction) {
self[MUTATE]!('replace cell', [index, original, newIdentifier]);
addToTransaction(_TAG);
}
return true;
},
deleteProperty(target: StableRecordIdentifier[], prop: string | symbol): boolean {
assert(`Deleting keys on managed arrays is disallowed`, transaction);
if (!transaction) {
return false;
}
return Reflect.deleteProperty(target, prop);
},
getPrototypeOf() {
return IdentifierArray.prototype;
},
}) as IdentifierArray;
if (DEPRECATE_A_USAGE) {
const meta = Ember.meta(this);
meta.hasMixin = (mixin: Object) => {
deprecate(`Do not call A() on EmberData RecordArrays`, false, {
id: 'ember-data:no-a-with-array-like',
until: '5.0',
since: { enabled: '4.7', available: '4.7' },
for: 'ember-data',
});
// @ts-expect-error ArrayMixin is more than a type
if (mixin === NativeArray || mixin === ArrayMixin) {
return true;
}
return false;
};
} else if (DEBUG) {
const meta = Ember.meta(this);
meta.hasMixin = (mixin: Object) => {
assert(`Do not call A() on EmberData RecordArrays`);
};
}
this[NOTIFY] = this[NOTIFY].bind(proxy);
return proxy;
}
/**
Used to get the latest version of all of the records in this array
from the adapter.
Example
```javascript
let people = store.peekAll('person');
people.isUpdating; // false
people.update().then(function() {
people.isUpdating; // false
});
people.isUpdating; // true
```
@method update
@public
*/
update(): PromiseArray<RecordInstance, IdentifierArray> | Promise<IdentifierArray> {
if (this.isUpdating) {
return this._updatingPromise!;
}
this.isUpdating = true;
let updatingPromise = this._update();
updatingPromise.finally(() => {
this._updatingPromise = null;
if (this.isDestroying || this.isDestroyed) {
return;
}
this.isUpdating = false;
});
this._updatingPromise = updatingPromise;
return updatingPromise;
}
/*
Update this RecordArray and return a promise which resolves once the update
is finished.
*/
_update(): PromiseArray<RecordInstance, IdentifierArray> | Promise<IdentifierArray> {
assert(`_update cannot be used with this array`, this.modelName);
return this.store.findAll(this.modelName, { reload: true });
}
// TODO deprecate
/**
Saves all of the records in the `RecordArray`.
Example
```javascript
let messages = store.peekAll('message');
messages.forEach(function(message) {
message.hasBeenSeen = true;
});
messages.save();
```
@method save
@public
@return {PromiseArray} promise
*/
save(): PromiseArray<RecordInstance, IdentifierArray> | Promise<IdentifierArray> {
let promise = Promise.all(this.map((record) => this.store.saveRecord(record))).then(() => this);
if (DEPRECATE_PROMISE_PROXIES) {
return promiseArray<RecordInstance, IdentifierArray>(promise);
}
return promise;
}
}
export default IdentifierArray;
if (DEPRECATE_SNAPSHOT_MODEL_CLASS_ACCESS) {
Object.defineProperty(IdentifierArray.prototype, 'type', {
get() {
deprecate(
`Using RecordArray.type to access the ModelClass for a record is deprecated. Use store.modelFor(<modelName>) instead.`,
false,
{
id: 'ember-data:deprecate-snapshot-model-class-access',
until: '5.0',
for: 'ember-data',
since: { available: '4.5.0', enabled: '4.5.0' },
}
);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (!this.modelName) {
return null;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
return this.store.modelFor(this.modelName);
},
});
}
export type CollectionCreateOptions = IdentifierArrayCreateOptions & {
query: ImmutableRequestInfo | Dict<unknown> | null;
isLoaded: boolean;
};
export class Collection extends IdentifierArray {
query: ImmutableRequestInfo | Dict<unknown> | null = null;
constructor(options: CollectionCreateOptions) {
super(options as IdentifierArrayCreateOptions);
this.query = options.query || null;
this.isLoaded = options.isLoaded || false;
}
_update(): PromiseArray<RecordInstance, Collection> | Promise<Collection> {
const { store, query } = this;
// TODO save options from initial request?
assert(`update cannot be used with this array`, this.modelName);
assert(`update cannot be used with no query`, query);
const promise = store.query(this.modelName, query as Dict<unknown>, { _recordArray: this });
if (DEPRECATE_PROMISE_PROXIES) {
return promiseArray(promise);
}
return promise;
}
destroy(clear: boolean) {
super.destroy(clear);
this._manager._managed.delete(this);
this._manager._pending.delete(this);
}
}
// trick the proxy "in" check
Collection.prototype.query = null;
// Ensure instanceof works correctly
//Object.setPrototypeOf(IdentifierArray.prototype, Array.prototype);
if (DEPRECATE_ARRAY_LIKE) {
IdentifierArray.prototype.DEPRECATED_CLASS_NAME = 'RecordArray';
Collection.prototype.DEPRECATED_CLASS_NAME = 'RecordArray';
const EmberObjectMethods = [
'addObserver',
'cacheFor',
'decrementProperty',
'get',
'getProperties',
'incrementProperty',
'notifyPropertyChange',
'removeObserver',
'set',
'setProperties',
'toggleProperty',
];
EmberObjectMethods.forEach((method) => {
IdentifierArray.prototype[method] = function delegatedMethod(...args: unknown[]): unknown {
deprecate(
`The EmberObject ${method} method on the class ${this.DEPRECATED_CLASS_NAME} is deprecated. Use dot-notation javascript get/set access instead.`,
false,
{
id: 'ember-data:deprecate-array-like',
until: '5.0',
since: { enabled: '4.7', available: '4.7' },
for: 'ember-data',
}
);
return (Ember[method] as (...args: unknown[]) => unknown)(this, ...args);
};
});
IdentifierArray.prototype.addObject = function (obj: RecordInstance) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'addObject', 'push');
let index = this.indexOf(obj);
if (index === -1) {
this.push(obj);
}
return this;
};
IdentifierArray.prototype.addObjects = function (objs: RecordInstance[]) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'addObjects', 'push');
objs.forEach((obj: RecordInstance) => {
let index = this.indexOf(obj);
if (index === -1) {
this.push(obj);
}
});
return this;
};
IdentifierArray.prototype.popObject = function () {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'popObject', 'pop');
return this.pop() as RecordInstance;
};
IdentifierArray.prototype.pushObject = function (obj: RecordInstance) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'pushObject', 'push');
this.push(obj);
return obj;
};
IdentifierArray.prototype.pushObjects = function (objs: RecordInstance[]) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'pushObjects', 'push');
this.push(...objs);
return this;
};
IdentifierArray.prototype.shiftObject = function () {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'shiftObject', 'shift');
return this.shift()!;
};
IdentifierArray.prototype.unshiftObject = function (obj: RecordInstance) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'unshiftObject', 'unshift');
this.unshift(obj);
return obj;
};
IdentifierArray.prototype.unshiftObjects = function (objs: RecordInstance[]) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'unshiftObjects', 'unshift');
this.unshift(...objs);
return this;
};
IdentifierArray.prototype.objectAt = function (index: number) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'objectAt', 'at');
//For negative index values go back from the end of the array
let arrIndex = Math.sign(index) === -1 ? this.length + index : index;
return this[arrIndex];
};
IdentifierArray.prototype.objectsAt = function (indeces: number[]) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'objectsAt', 'at');
return indeces.map((index) => this.objectAt(index)!);
};
IdentifierArray.prototype.removeAt = function (index: number) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'removeAt', 'splice');
this.splice(index, 1);
return this;
};
IdentifierArray.prototype.insertAt = function (index: number, obj: RecordInstance) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'insertAt', 'splice');
this.splice(index, 0, obj);
return this;
};
IdentifierArray.prototype.removeObject = function (obj: RecordInstance) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'removeObject', 'splice');
const index = this.indexOf(obj);
if (index !== -1) {
this.splice(index, 1);
}
return this;
};
IdentifierArray.prototype.removeObjects = function (objs: RecordInstance[]) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'removeObjects', 'splice');
objs.forEach((obj) => {
const index = this.indexOf(obj);
if (index !== -1) {
this.splice(index, 1);
}
});
return this;
};
IdentifierArray.prototype.toArray = function () {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'toArray', 'slice');
return this.slice();
};
IdentifierArray.prototype.replace = function (idx: number, amt: number, objects?: RecordInstance[]) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'replace', 'splice');
if (objects) {
this.splice(idx, amt, ...objects);
} else {
this.splice(idx, amt);
}
};
IdentifierArray.prototype.clear = function () {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'clear', 'length = 0');
this.splice(0, this.length);
return this;
};
IdentifierArray.prototype.setObjects = function (objects: RecordInstance[]) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'setObjects', '`arr.length = 0; arr.push(objects);`');
assert(
`${this.DEPRECATED_CLASS_NAME}.setObjects expects to receive an array as its argument`,
Array.isArray(objects)
);
this.splice(0, this.length);
this.push(...objects);
return this;
};
IdentifierArray.prototype.reverseObjects = function () {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'reverseObjects', 'reverse');
this.reverse();
return this;
};
IdentifierArray.prototype.compact = function () {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'compact', 'filter');
return this.filter((v) => v !== null && v !== undefined);
};
IdentifierArray.prototype.any = function (callback, target) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'any', 'some');
return this.some(callback, target);
};
IdentifierArray.prototype.isAny = function (prop, value) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'isAny', 'some');
let hasValue = arguments.length === 2;
return this.some((v) => (hasValue ? v[prop] === value : v[prop] === true));
};
IdentifierArray.prototype.isEvery = function (prop, value) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'isEvery', 'every');
let hasValue = arguments.length === 2;
return this.every((v) => (hasValue ? v[prop] === value : v[prop] === true));
};
IdentifierArray.prototype.getEach = function (key: string) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'getEach', 'map');
return this.map((value) => get(value, key));
};
IdentifierArray.prototype.mapBy = function (key: string) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'mapBy', 'map');
return this.map((value) => get(value, key));
};
IdentifierArray.prototype.findBy = function (key: string, value?: unknown) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'findBy', 'find');
if (arguments.length === 2) {
return this.find((val) => {
return get(val, key) === value;
});
} else {
return this.find((val) => Boolean(get(val, key)));
}
};
IdentifierArray.prototype.filterBy = function (key: string, value?: unknown) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'filterBy', 'filter');
if (arguments.length === 2) {
return this.filter((record) => {
return get(record, key) === value;
});
}
return this.filter((record) => {
return Boolean(get(record, key));
});
};
IdentifierArray.prototype.sortBy = function (...sortKeys: string[]) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'sortBy', '.slice().sort');
return this.slice().sort((a, b) => {
for (let i = 0; i < sortKeys.length; i++) {
let key = sortKeys[i];
let propA = get(a, key);
let propB = get(b, key);
// return 1 or -1 else continue to the next sortKey
let compareValue = compare(propA, propB);
if (compareValue) {
return compareValue;
}
}
return 0;
});
};
// @ts-expect-error
IdentifierArray.prototype.invoke = function (key: string, ...args: unknown[]) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'invoke', 'forEach');
return this.map((value) => (value[key] as (...args: unknown[]) => unknown)(...args));
};
// @ts-expect-error
IdentifierArray.prototype.addArrayObserver = function () {
deprecateArrayLike(
this.DEPRECATED_CLASS_NAME,
'addArrayObserver',
'derived state or reacting at the change source'
);
};
// @ts-expect-error
IdentifierArray.prototype.removeArrayObserver = function () {
deprecateArrayLike(
this.DEPRECATED_CLASS_NAME,
'removeArrayObserver',
'derived state or reacting at the change source'
);
};
// @ts-expect-error
IdentifierArray.prototype.arrayContentWillChange = function () {
deprecateArrayLike(
this.DEPRECATED_CLASS_NAME,
'arrayContentWillChange',
'derived state or reacting at the change source'
);
};
// @ts-expect-error
IdentifierArray.prototype.arrayContentDidChange = function () {
deprecateArrayLike(
this.DEPRECATED_CLASS_NAME,
'arrayContentDidChange',
'derived state or reacting at the change source.'
);
};
IdentifierArray.prototype.reject = function (callback, target?: unknown) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'reject', 'filter');
assert('`reject` expects a function as first argument.', typeof callback === 'function');
return this.filter((...args) => {
return !callback.apply(target, args);
});
};
IdentifierArray.prototype.rejectBy = function (key: string, value?: unknown) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'rejectBy', 'filter');
if (arguments.length === 2) {
return this.filter((record) => {
return get(record, key) !== value;
});
}
return this.filter((record) => {
return !get(record, key);
});
};
IdentifierArray.prototype.setEach = function (key: string, value: unknown) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'setEach', 'forEach');
this.forEach((item) => set(item, key, value));
};
IdentifierArray.prototype.uniq = function () {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'uniq', 'filter');
// all current managed arrays are already enforced as unique
return this.slice();
};
// @ts-expect-error
IdentifierArray.prototype.uniqBy = function (key: string) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'uniqBy', 'filter');
// all current managed arrays are already enforced as unique
let seen = new Set();
let result: RecordInstance[] = [];
this.forEach((item) => {
let value = get(item, key);
if (seen.has(value)) {
return;
}
seen.add(value);
result.push(item);
});
return result;
};
IdentifierArray.prototype.without = function (value: RecordInstance) {
deprecateArrayLike(this.DEPRECATED_CLASS_NAME, 'without', 'slice');
const newArr = this.slice();
const index = this.indexOf(value);
if (index !== -1) {
newArr.splice(index, 1);
}
return newArr;
};
// @ts-expect-error
IdentifierArray.prototype.firstObject = null;
// @ts-expect-error
IdentifierArray.prototype.lastObject = null;
}
type PromiseProxyRecord = { then(): void; content: RecordInstance | null | undefined };
function assertRecordPassedToHasMany(record: RecordInstance | PromiseProxyRecord) {
assert(
`All elements of a hasMany relationship must be instances of Model, you passed $${typeof record}`,
(function () {
try {
recordIdentifierFor(record);
return true;
} catch {
return false;