@ember-data/model 4.10.0-alpha.2 → 4.10.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/addon/{-private/diff-array.ts → -private.js} +41 -13
  2. package/addon/-private.js.map +1 -0
  3. package/addon/has-many-357b6265.js +6277 -0
  4. package/addon/has-many-357b6265.js.map +1 -0
  5. package/addon/index.js +1 -0
  6. package/addon/index.js.map +1 -0
  7. package/addon-main.js +90 -0
  8. package/package.json +43 -15
  9. package/addon/-private/attr.js +0 -162
  10. package/addon/-private/belongs-to.js +0 -268
  11. package/addon/-private/debug/assert-polymorphic-type.js +0 -71
  12. package/addon/-private/deprecated-promise-proxy.ts +0 -76
  13. package/addon/-private/errors.ts +0 -425
  14. package/addon/-private/has-many.js +0 -280
  15. package/addon/-private/index.ts +0 -14
  16. package/addon/-private/legacy-data-fetch.js +0 -395
  17. package/addon/-private/legacy-data-utils.ts +0 -92
  18. package/addon/-private/legacy-relationships-support.ts +0 -774
  19. package/addon/-private/many-array.ts +0 -401
  20. package/addon/-private/model-for-mixin.ts +0 -38
  21. package/addon/-private/model.js +0 -2516
  22. package/addon/-private/notify-changes.ts +0 -72
  23. package/addon/-private/promise-belongs-to.ts +0 -73
  24. package/addon/-private/promise-many-array.ts +0 -425
  25. package/addon/-private/promise-proxy-base.js +0 -4
  26. package/addon/-private/record-state.ts +0 -468
  27. package/addon/-private/references/belongs-to.ts +0 -624
  28. package/addon/-private/references/has-many.ts +0 -669
  29. package/addon/-private/relationship-meta.ts +0 -98
  30. package/addon/-private/util.ts +0 -31
  31. package/addon/index.ts +0 -39
  32. package/blueprints/model/HELP.md +0 -26
  33. package/blueprints/model/files/__root__/__path__/__name__.js +0 -5
  34. package/blueprints/model/index.js +0 -158
  35. package/blueprints/model/native-files/__root__/__path__/__name__.js +0 -5
  36. package/blueprints/model-test/index.js +0 -33
  37. package/blueprints/model-test/mocha-files/__root__/__path__/__test__.js +0 -18
  38. package/blueprints/model-test/mocha-rfc-232-files/__root__/__path__/__test__.js +0 -15
  39. package/blueprints/model-test/qunit-files/__root__/__path__/__test__.js +0 -14
  40. package/index.js +0 -47
@@ -1,669 +0,0 @@
1
- import { deprecate } from '@ember/debug';
2
- import { dependentKeyCompat } from '@ember/object/compat';
3
- import { DEBUG } from '@glimmer/env';
4
- import { cached, tracked } from '@glimmer/tracking';
5
-
6
- import type { Object as JSONObject, Value as JSONValue } from 'json-typescript';
7
- import { resolve } from 'rsvp';
8
-
9
- import { ManyArray } from 'ember-data/-private';
10
-
11
- import { DEPRECATE_PROMISE_PROXIES } from '@ember-data/private-build-infra/deprecations';
12
- import type { Graph } from '@ember-data/record-data/-private/graph/graph';
13
- import type ManyRelationship from '@ember-data/record-data/-private/relationships/state/has-many';
14
- import type Store from '@ember-data/store';
15
- import { recordIdentifierFor } from '@ember-data/store';
16
- import type { NotificationType } from '@ember-data/store/-private/managers/record-notification-manager';
17
- import type {
18
- CollectionResourceDocument,
19
- CollectionResourceRelationship,
20
- ExistingResourceObject,
21
- LinkObject,
22
- PaginationLinks,
23
- SingleResourceDocument,
24
- } from '@ember-data/types/q/ember-data-json-api';
25
- import type { StableRecordIdentifier } from '@ember-data/types/q/identifier';
26
- import type { RecordInstance } from '@ember-data/types/q/record-instance';
27
- import type { FindOptions } from '@ember-data/types/q/store';
28
- import type { Dict } from '@ember-data/types/q/utils';
29
-
30
- import { assertPolymorphicType } from '../debug/assert-polymorphic-type';
31
- import type { LegacySupport } from '../legacy-relationships-support';
32
- import { LEGACY_SUPPORT } from '../model';
33
-
34
- /**
35
- @module @ember-data/model
36
- */
37
- interface ResourceIdentifier {
38
- links?: {
39
- related?: string | LinkObject;
40
- };
41
- meta?: JSONObject;
42
- }
43
-
44
- function isResourceIdentiferWithRelatedLinks(
45
- value: CollectionResourceRelationship | ResourceIdentifier | null
46
- ): value is ResourceIdentifier & { links: { related: string | LinkObject | null } } {
47
- return Boolean(value && value.links && value.links.related);
48
- }
49
- /**
50
- A `HasManyReference` is a low-level API that allows users and addon
51
- authors to perform meta-operations on a has-many relationship.
52
-
53
- @class HasManyReference
54
- @public
55
- @extends Reference
56
- */
57
- export default class HasManyReference {
58
- declare graph: Graph;
59
- declare key: string;
60
- declare hasManyRelationship: ManyRelationship;
61
- declare type: string;
62
- declare store: Store;
63
-
64
- // unsubscribe tokens given to us by the notification manager
65
- ___token!: Object;
66
- ___identifier: StableRecordIdentifier;
67
- ___relatedTokenMap!: Map<StableRecordIdentifier, Object>;
68
-
69
- @tracked _ref = 0;
70
-
71
- constructor(
72
- store: Store,
73
- graph: Graph,
74
- parentIdentifier: StableRecordIdentifier,
75
- hasManyRelationship: ManyRelationship,
76
- key: string
77
- ) {
78
- this.graph = graph;
79
- this.key = key;
80
- this.hasManyRelationship = hasManyRelationship;
81
- this.type = hasManyRelationship.definition.type;
82
-
83
- this.store = store;
84
- this.___identifier = parentIdentifier;
85
- this.___token = store._notificationManager.subscribe(
86
- parentIdentifier,
87
- (_: StableRecordIdentifier, bucket: NotificationType, notifiedKey?: string) => {
88
- if (bucket === 'relationships' && notifiedKey === key) {
89
- this._ref++;
90
- }
91
- }
92
- );
93
- this.___relatedTokenMap = new Map();
94
- // TODO inverse
95
- }
96
-
97
- destroy() {
98
- this.store._notificationManager.unsubscribe(this.___token);
99
- this.___relatedTokenMap.forEach((token) => {
100
- this.store._notificationManager.unsubscribe(token);
101
- });
102
- this.___relatedTokenMap.clear();
103
- }
104
-
105
- /**
106
- * An array of identifiers for the records that this reference refers to.
107
- *
108
- * @property {StableRecordIdentifier[]} identifiers
109
- * @public
110
- */
111
- @cached
112
- @dependentKeyCompat
113
- get identifiers(): StableRecordIdentifier[] {
114
- this._ref; // consume the tracked prop
115
-
116
- let resource = this._resource();
117
-
118
- let map = this.___relatedTokenMap;
119
- this.___relatedTokenMap = new Map();
120
-
121
- if (resource && resource.data) {
122
- return resource.data.map((resourceIdentifier) => {
123
- const identifier = this.store.identifierCache.getOrCreateRecordIdentifier(resourceIdentifier);
124
- let token = map.get(identifier);
125
-
126
- if (token) {
127
- map.delete(identifier);
128
- } else {
129
- token = this.store._notificationManager.subscribe(
130
- identifier,
131
- (_: StableRecordIdentifier, bucket: NotificationType, notifiedKey?: string) => {
132
- if (bucket === 'identity' || (bucket === 'attributes' && notifiedKey === 'id')) {
133
- this._ref++;
134
- }
135
- }
136
- );
137
- }
138
- this.___relatedTokenMap.set(identifier, token);
139
-
140
- return identifier;
141
- });
142
- }
143
-
144
- map.forEach((token) => {
145
- this.store._notificationManager.unsubscribe(token);
146
- });
147
- map.clear();
148
-
149
- return [];
150
- }
151
-
152
- _resource() {
153
- return this.store._instanceCache
154
- .getRecordData(this.___identifier)
155
- .getRelationship(this.___identifier, this.key) as CollectionResourceRelationship;
156
- }
157
-
158
- /**
159
- This returns a string that represents how the reference will be
160
- looked up when it is loaded. If the relationship has a link it will
161
- use the "link" otherwise it defaults to "id".
162
-
163
- Example
164
-
165
- ```app/models/post.js
166
- import Model, { hasMany } from '@ember-data/model';
167
-
168
- export default class PostModel extends Model {
169
- @hasMany('comment', { async: true, inverse: null }) comments;
170
- }
171
- ```
172
-
173
- ```javascript
174
- let post = store.push({
175
- data: {
176
- type: 'post',
177
- id: 1,
178
- relationships: {
179
- comments: {
180
- data: [{ type: 'comment', id: 1 }]
181
- }
182
- }
183
- }
184
- });
185
-
186
- let commentsRef = post.hasMany('comments');
187
-
188
- // get the identifier of the reference
189
- if (commentsRef.remoteType() === "ids") {
190
- let ids = commentsRef.ids();
191
- } else if (commentsRef.remoteType() === "link") {
192
- let link = commentsRef.link();
193
- }
194
- ```
195
-
196
- @method remoteType
197
- @public
198
- @return {String} The name of the remote type. This should either be `link` or `ids`
199
- */
200
- remoteType(): 'link' | 'ids' {
201
- let value = this._resource();
202
- if (value && value.links && value.links.related) {
203
- return 'link';
204
- }
205
-
206
- return 'ids';
207
- }
208
-
209
- /**
210
- `ids()` returns an array of the record IDs in this relationship.
211
-
212
- Example
213
-
214
- ```app/models/post.js
215
- import Model, { hasMany } from '@ember-data/model';
216
-
217
- export default class PostModel extends Model {
218
- @hasMany('comment', { async: true, inverse: null }) comments;
219
- }
220
- ```
221
-
222
- ```javascript
223
- let post = store.push({
224
- data: {
225
- type: 'post',
226
- id: 1,
227
- relationships: {
228
- comments: {
229
- data: [{ type: 'comment', id: 1 }]
230
- }
231
- }
232
- }
233
- });
234
-
235
- let commentsRef = post.hasMany('comments');
236
-
237
- commentsRef.ids(); // ['1']
238
- ```
239
-
240
- @method ids
241
- @public
242
- @return {Array} The ids in this has-many relationship
243
- */
244
- ids(): Array<string | null> {
245
- return this.identifiers.map((identifier) => identifier.id);
246
- }
247
-
248
- /**
249
- The link Ember Data will use to fetch or reload this belongs-to
250
- relationship. By default it uses only the "related" resource linkage.
251
-
252
- Example
253
-
254
- ```javascript
255
- // models/blog.js
256
- import Model, { belongsTo } from '@ember-data/model';
257
- export default Model.extend({
258
- user: belongsTo('user', { async: true, inverse: null })
259
- });
260
-
261
- let blog = store.push({
262
- data: {
263
- type: 'blog',
264
- id: 1,
265
- relationships: {
266
- user: {
267
- links: {
268
- related: '/articles/1/author'
269
- }
270
- }
271
- }
272
- }
273
- });
274
- let userRef = blog.belongsTo('user');
275
-
276
- // get the identifier of the reference
277
- if (userRef.remoteType() === "link") {
278
- let link = userRef.link();
279
- }
280
- ```
281
-
282
- @method link
283
- @public
284
- @return {String} The link Ember Data will use to fetch or reload this belongs-to relationship.
285
- */
286
- link(): string | null {
287
- let resource = this._resource();
288
-
289
- if (isResourceIdentiferWithRelatedLinks(resource)) {
290
- if (resource.links) {
291
- let related = resource.links.related;
292
- return !related || typeof related === 'string' ? related : related.href;
293
- }
294
- }
295
- return null;
296
- }
297
-
298
- /**
299
- * any links that have been received for this relationship
300
- *
301
- * @method links
302
- * @public
303
- * @returns
304
- */
305
- links(): PaginationLinks | null {
306
- let resource = this._resource();
307
-
308
- return resource && resource.links ? resource.links : null;
309
- }
310
-
311
- /**
312
- The meta data for the has-many relationship.
313
-
314
- Example
315
-
316
- ```javascript
317
- // models/blog.js
318
- import Model, { hasMany } from '@ember-data/model';
319
- export default Model.extend({
320
- users: hasMany('user', { async: true, inverse: null })
321
- });
322
-
323
- let blog = store.push({
324
- data: {
325
- type: 'blog',
326
- id: 1,
327
- relationships: {
328
- users: {
329
- links: {
330
- related: {
331
- href: '/articles/1/authors'
332
- },
333
- },
334
- meta: {
335
- lastUpdated: 1458014400000
336
- }
337
- }
338
- }
339
- }
340
- });
341
-
342
- let usersRef = blog.hasMany('user');
343
-
344
- usersRef.meta() // { lastUpdated: 1458014400000 }
345
- ```
346
-
347
- @method meta
348
- @public
349
- @return {Object} The meta information for the belongs-to relationship.
350
- */
351
- meta() {
352
- let meta: Dict<JSONValue> | null = null;
353
- let resource = this._resource();
354
- if (resource && resource.meta && typeof resource.meta === 'object') {
355
- meta = resource.meta;
356
- }
357
- return meta;
358
- }
359
-
360
- /**
361
- `push` can be used to update the data in the relationship and Ember
362
- Data will treat the new data as the canonical value of this
363
- relationship on the backend.
364
-
365
- Example
366
-
367
- ```app/models/post.js
368
- import Model, { hasMany } from '@ember-data/model';
369
-
370
- export default class PostModel extends Model {
371
- @hasMany('comment', { async: true, inverse: null }) comments;
372
- }
373
- ```
374
-
375
- ```
376
- let post = store.push({
377
- data: {
378
- type: 'post',
379
- id: 1,
380
- relationships: {
381
- comments: {
382
- data: [{ type: 'comment', id: 1 }]
383
- }
384
- }
385
- }
386
- });
387
-
388
- let commentsRef = post.hasMany('comments');
389
-
390
- commentsRef.ids(); // ['1']
391
-
392
- commentsRef.push([
393
- [{ type: 'comment', id: 2 }],
394
- [{ type: 'comment', id: 3 }],
395
- ])
396
-
397
- commentsRef.ids(); // ['2', '3']
398
- ```
399
-
400
- @method push
401
- @public
402
- @param {Array|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship.
403
- @return {ManyArray}
404
- */
405
- async push(
406
- objectOrPromise: ExistingResourceObject[] | CollectionResourceDocument | { data: SingleResourceDocument[] }
407
- ): Promise<ManyArray> {
408
- let payload = objectOrPromise;
409
- if (DEPRECATE_PROMISE_PROXIES) {
410
- if ((objectOrPromise as unknown as { then: unknown }).then) {
411
- payload = await resolve(objectOrPromise);
412
- if (payload !== objectOrPromise) {
413
- deprecate(
414
- `You passed in a Promise to a Reference API that now expects a resolved value. await the value before setting it.`,
415
- false,
416
- {
417
- id: 'ember-data:deprecate-promise-proxies',
418
- until: '5.0',
419
- since: {
420
- enabled: '4.7',
421
- available: '4.7',
422
- },
423
- for: 'ember-data',
424
- }
425
- );
426
- }
427
- }
428
- }
429
- let array: Array<ExistingResourceObject | SingleResourceDocument>;
430
-
431
- if (!Array.isArray(payload) && typeof payload === 'object' && Array.isArray(payload.data)) {
432
- array = payload.data;
433
- } else {
434
- array = payload as ExistingResourceObject[];
435
- }
436
-
437
- const { store } = this;
438
-
439
- let identifiers = array.map((obj) => {
440
- let record: RecordInstance;
441
- if ('data' in obj) {
442
- // TODO deprecate pushing non-valid JSON:API here
443
- record = store.push(obj);
444
- } else {
445
- record = store.push({ data: obj });
446
- }
447
-
448
- if (DEBUG) {
449
- let relationshipMeta = this.hasManyRelationship.definition;
450
- let identifier = this.hasManyRelationship.identifier;
451
-
452
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
453
- assertPolymorphicType(identifier, relationshipMeta, recordIdentifierFor(record), store);
454
- }
455
- return recordIdentifierFor(record);
456
- });
457
-
458
- const { identifier } = this.hasManyRelationship;
459
- store._join(() => {
460
- this.graph.push({
461
- op: 'replaceRelatedRecords',
462
- record: identifier,
463
- field: this.key,
464
- value: identifiers,
465
- });
466
- });
467
-
468
- return this.load();
469
- }
470
-
471
- _isLoaded() {
472
- let hasRelationshipDataProperty = this.hasManyRelationship.state.hasReceivedData;
473
- if (!hasRelationshipDataProperty) {
474
- return false;
475
- }
476
-
477
- let localState = this.hasManyRelationship.localState;
478
-
479
- return localState.every((identifier) => {
480
- return this.store._instanceCache.recordIsLoaded(identifier, true) === true;
481
- });
482
- }
483
-
484
- /**
485
- `value()` synchronously returns the current value of the has-many
486
- relationship. Unlike `record.relationshipName`, calling
487
- `value()` on a reference does not trigger a fetch if the async
488
- relationship is not yet loaded. If the relationship is not loaded
489
- it will always return `null`.
490
-
491
- Example
492
-
493
- ```app/models/post.js
494
- import Model, { hasMany } from '@ember-data/model';
495
-
496
- export default class PostModel extends Model {
497
- @hasMany('comment', { async: true, inverse: null }) comments;
498
- }
499
- ```
500
-
501
- ```javascript
502
- let post = store.push({
503
- data: {
504
- type: 'post',
505
- id: 1,
506
- relationships: {
507
- comments: {
508
- data: [{ type: 'comment', id: 1 }]
509
- }
510
- }
511
- }
512
- });
513
-
514
- let commentsRef = post.hasMany('comments');
515
-
516
- post.comments.then(function(comments) {
517
- commentsRef.value() === comments
518
- })
519
- ```
520
-
521
- @method value
522
- @public
523
- @return {ManyArray}
524
- */
525
- value() {
526
- const support: LegacySupport = (LEGACY_SUPPORT as Map<StableRecordIdentifier, LegacySupport>).get(
527
- this.___identifier
528
- )!;
529
-
530
- const loaded = this._isLoaded();
531
-
532
- if (!loaded) {
533
- // subscribe to changes
534
- // for when we are not loaded yet
535
- this._ref;
536
- return null;
537
- }
538
-
539
- return support.getManyArray(this.key);
540
- }
541
-
542
- /**
543
- Loads the relationship if it is not already loaded. If the
544
- relationship is already loaded this method does not trigger a new
545
- load. This causes a request to the specified
546
- relationship link or reloads all items currently in the relationship.
547
-
548
- Example
549
-
550
- ```app/models/post.js
551
- import Model, { hasMany } from '@ember-data/model';
552
-
553
- export default class PostModel extends Model {
554
- @hasMany('comment', { async: true, inverse: null }) comments;
555
- }
556
- ```
557
-
558
- ```javascript
559
- let post = store.push({
560
- data: {
561
- type: 'post',
562
- id: 1,
563
- relationships: {
564
- comments: {
565
- data: [{ type: 'comment', id: 1 }]
566
- }
567
- }
568
- }
569
- });
570
-
571
- let commentsRef = post.hasMany('comments');
572
-
573
- commentsRef.load().then(function(comments) {
574
- //...
575
- });
576
- ```
577
-
578
- You may also pass in an options object whose properties will be
579
- fed forward. This enables you to pass `adapterOptions` into the
580
- request given to the adapter via the reference.
581
-
582
- Example
583
-
584
- ```javascript
585
- commentsRef.load({ adapterOptions: { isPrivate: true } })
586
- .then(function(comments) {
587
- //...
588
- });
589
- ```
590
-
591
- ```app/adapters/comment.js
592
- export default ApplicationAdapter.extend({
593
- findMany(store, type, id, snapshots) {
594
- // In the adapter you will have access to adapterOptions.
595
- let adapterOptions = snapshots[0].adapterOptions;
596
- }
597
- });
598
- ```
599
-
600
- @method load
601
- @public
602
- @param {Object} options the options to pass in.
603
- @return {Promise} a promise that resolves with the ManyArray in
604
- this has-many relationship.
605
- */
606
- async load(options?: FindOptions): Promise<ManyArray> {
607
- const support: LegacySupport = (LEGACY_SUPPORT as Map<StableRecordIdentifier, LegacySupport>).get(
608
- this.___identifier
609
- )!;
610
- return support.getHasMany(this.key, options) as Promise<ManyArray> | ManyArray; // this cast is necessary because typescript does not work properly with custom thenables;
611
- }
612
-
613
- /**
614
- Reloads this has-many relationship. This causes a request to the specified
615
- relationship link or reloads all items currently in the relationship.
616
-
617
- Example
618
-
619
- ```app/models/post.js
620
- import Model, { hasMany } from '@ember-data/model';
621
-
622
- export default class PostModel extends Model {
623
- @hasMany('comment', { async: true, inverse: null }) comments;
624
- }
625
- ```
626
-
627
- ```javascript
628
- let post = store.push({
629
- data: {
630
- type: 'post',
631
- id: 1,
632
- relationships: {
633
- comments: {
634
- data: [{ type: 'comment', id: 1 }]
635
- }
636
- }
637
- }
638
- });
639
-
640
- let commentsRef = post.hasMany('comments');
641
-
642
- commentsRef.reload().then(function(comments) {
643
- //...
644
- });
645
- ```
646
-
647
- You may also pass in an options object whose properties will be
648
- fed forward. This enables you to pass `adapterOptions` into the
649
- request given to the adapter via the reference. A full example
650
- can be found in the `load` method.
651
-
652
- Example
653
-
654
- ```javascript
655
- commentsRef.reload({ adapterOptions: { isPrivate: true } })
656
- ```
657
-
658
- @method reload
659
- @public
660
- @param {Object} options the options to pass in.
661
- @return {Promise} a promise that resolves with the ManyArray in this has-many relationship.
662
- */
663
- reload(options?: FindOptions) {
664
- const support: LegacySupport = (LEGACY_SUPPORT as Map<StableRecordIdentifier, LegacySupport>).get(
665
- this.___identifier
666
- )!;
667
- return support.reloadHasMany(this.key, options);
668
- }
669
- }