-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathmany-array.ts
382 lines (330 loc) · 10.1 KB
/
many-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
/**
@module @ember-data/store
*/
import { assert } from '@ember/debug';
import type Store from '@ember-data/store';
import {
ARRAY_SIGNAL,
MUTATE,
notifyArray,
RecordArray,
recordIdentifierFor,
SOURCE,
} from '@ember-data/store/-private';
import { IdentifierArrayCreateOptions } from '@ember-data/store/-private/record-arrays/identifier-array';
import type { CreateRecordProperties } from '@ember-data/store/-private/store-service';
import type { Cache } from '@ember-data/types/q/cache';
import type { ModelSchema } from '@ember-data/types/q/ds-model';
import type { 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 type { FindOptions } from '@ember-data/types/q/store';
import { LegacySupport } from './legacy-relationships-support';
export interface ManyArrayCreateArgs {
identifiers: StableRecordIdentifier[];
type: string;
store: Store;
allowMutation: boolean;
manager: LegacySupport;
identifier: StableRecordIdentifier;
cache: Cache;
meta: Record<string, unknown> | null;
links: Links | PaginationLinks | null;
key: string;
isPolymorphic: boolean;
isAsync: boolean;
_inverseIsAsync: boolean;
isLoaded: boolean;
}
/**
A `ManyArray` is a `MutableArray` that represents the contents of a has-many
relationship.
The `ManyArray` is instantiated lazily the first time the relationship is
requested.
This class is not intended to be directly instantiated by consuming applications.
### Inverses
Often, the relationships in Ember Data applications will have
an inverse. For example, imagine the following models are
defined:
```app/models/post.js
import Model, { hasMany } from '@ember-data/model';
export default class PostModel extends Model {
@hasMany('comment') comments;
}
```
```app/models/comment.js
import Model, { belongsTo } from '@ember-data/model';
export default class CommentModel extends Model {
@belongsTo('post') post;
}
```
If you created a new instance of `Post` and added
a `Comment` record to its `comments` has-many
relationship, you would expect the comment's `post`
property to be set to the post that contained
the has-many.
We call the record to which a relationship belongs-to the
relationship's _owner_.
@class ManyArray
@public
*/
export default class RelatedCollection extends RecordArray {
declare isAsync: boolean;
/**
The loading state of this array
@property {Boolean} isLoaded
@public
*/
declare isLoaded: boolean;
/**
`true` if the relationship is polymorphic, `false` otherwise.
@property {Boolean} isPolymorphic
@private
*/
declare isPolymorphic: boolean;
declare _inverseIsAsync: boolean;
/**
Metadata associated with the request for async hasMany relationships.
Example
Given that the server returns the following JSON payload when fetching a
hasMany relationship:
```js
{
"comments": [{
"id": 1,
"comment": "This is the first comment",
}, {
// ...
}],
"meta": {
"page": 1,
"total": 5
}
}
```
You can then access the meta data via the `meta` property:
```js
let comments = await post.comments;
let meta = comments.meta;
// meta.page => 1
// meta.total => 5
```
@property {Object | null} meta
@public
*/
declare meta: Record<string, unknown> | null;
/**
* Retrieve the links for this relationship
*
@property {Object | null} links
@public
*/
declare links: Links | PaginationLinks | null;
declare identifier: StableRecordIdentifier;
declare cache: Cache;
// @ts-expect-error
declare _manager: LegacySupport;
declare store: Store;
declare key: string;
declare type: ModelSchema;
constructor(options: ManyArrayCreateArgs) {
super(options as unknown as IdentifierArrayCreateOptions);
this.isLoaded = options.isLoaded || false;
this.isAsync = options.isAsync || false;
this.isPolymorphic = options.isPolymorphic || false;
this.identifier = options.identifier;
this.key = options.key;
}
[MUTATE](prop: string, args: unknown[], result?: unknown) {
switch (prop) {
case 'length 0': {
this._manager.mutate({
op: 'replaceRelatedRecords',
record: this.identifier,
field: this.key,
value: [],
});
break;
}
case 'replace cell': {
const [index, prior, value] = args as [number, StableRecordIdentifier, StableRecordIdentifier];
this._manager.mutate({
op: 'replaceRelatedRecord',
record: this.identifier,
field: this.key,
value,
prior,
index,
});
break;
}
case 'push':
this._manager.mutate({
op: 'addToRelatedRecords',
record: this.identifier,
field: this.key,
value: extractIdentifiersFromRecords(args),
});
break;
case 'pop':
if (result) {
this._manager.mutate({
op: 'removeFromRelatedRecords',
record: this.identifier,
field: this.key,
value: recordIdentifierFor(result as RecordInstance),
});
}
break;
case 'unshift':
this._manager.mutate({
op: 'addToRelatedRecords',
record: this.identifier,
field: this.key,
value: extractIdentifiersFromRecords(args),
index: 0,
});
break;
case 'shift':
if (result) {
this._manager.mutate({
op: 'removeFromRelatedRecords',
record: this.identifier,
field: this.key,
value: recordIdentifierFor(result as RecordInstance),
index: 0,
});
}
break;
case 'sort':
this._manager.mutate({
op: 'sortRelatedRecords',
record: this.identifier,
field: this.key,
value: (result as RecordInstance[]).map(recordIdentifierFor),
});
break;
case 'splice': {
const [start, removeCount, ...adds] = args as [number, number, RecordInstance];
// detect a full replace
if (removeCount > 0 && adds.length === this[SOURCE].length) {
this._manager.mutate({
op: 'replaceRelatedRecords',
record: this.identifier,
field: this.key,
value: extractIdentifiersFromRecords(adds),
});
return;
}
if (removeCount > 0) {
this._manager.mutate({
op: 'removeFromRelatedRecords',
record: this.identifier,
field: this.key,
value: (result as RecordInstance[]).map(recordIdentifierFor),
index: start,
});
}
if (adds?.length) {
this._manager.mutate({
op: 'addToRelatedRecords',
record: this.identifier,
field: this.key,
value: extractIdentifiersFromRecords(adds),
index: start,
});
}
break;
}
default:
assert(`unable to convert ${prop} into a transaction that updates the cache state for this record array`);
}
}
notify() {
const signal = this[ARRAY_SIGNAL];
signal.shouldReset = true;
// @ts-expect-error
notifyArray(this);
}
/**
Reloads all of the records in the manyArray. If the manyArray
holds a relationship that was originally fetched using a links url
Ember Data will revisit the original links url to repopulate the
relationship.
If the manyArray holds the result of a `store.query()` reload will
re-run the original query.
Example
```javascript
let user = store.peekRecord('user', '1')
await login(user);
let permissions = await user.permissions;
await permissions.reload();
```
@method reload
@public
*/
reload(options?: FindOptions) {
// TODO this is odd, we don't ask the store for anything else like this?
return this._manager.reloadHasMany(this.key, options);
}
/**
Saves all of the records in the `ManyArray`.
Example
```javascript
let inbox = await store.findRecord('inbox', '1');
let messages = await inbox.messages;
messages.forEach((message) => {
message.isRead = true;
});
messages.save();
```
@method save
@public
@return {PromiseArray} promise
*/
/**
Create a child record within the owner
@method createRecord
@public
@param {Object} hash
@return {Model} record
*/
createRecord(hash: CreateRecordProperties): RecordInstance {
const { store } = this;
assert(`Expected modelName to be set`, this.modelName);
const record = store.createRecord(this.modelName, hash);
this.push(record);
return record;
}
destroy() {
super.destroy(false);
}
}
RelatedCollection.prototype.isAsync = false;
RelatedCollection.prototype.isPolymorphic = false;
RelatedCollection.prototype.identifier = null as unknown as StableRecordIdentifier;
RelatedCollection.prototype.cache = null as unknown as Cache;
RelatedCollection.prototype._inverseIsAsync = false;
RelatedCollection.prototype.key = '';
RelatedCollection.prototype.DEPRECATED_CLASS_NAME = 'ManyArray';
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;
}
})()
);
}
function extractIdentifiersFromRecords(records: RecordInstance[]): StableRecordIdentifier[] {
return records.map(extractIdentifierFromRecord);
}
function extractIdentifierFromRecord(recordOrPromiseRecord: PromiseProxyRecord | RecordInstance) {
assertRecordPassedToHasMany(recordOrPromiseRecord);
return recordIdentifierFor(recordOrPromiseRecord);
}