@ember-data/model 5.6.0-alpha.5 → 5.6.0-beta.1

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 (74) hide show
  1. package/addon-main.cjs +1 -1
  2. package/dist/-private.js +1 -2
  3. package/dist/hooks.js +1 -2
  4. package/dist/index.js +1 -667
  5. package/dist/migration-support.js +1 -381
  6. package/package.json +7 -31
  7. package/unstable-preview-types/-private.d.ts +3 -8
  8. package/unstable-preview-types/hooks.d.ts +3 -4
  9. package/unstable-preview-types/index.d.ts +31 -66
  10. package/unstable-preview-types/migration-support.d.ts +21 -263
  11. package/dist/-private.js.map +0 -1
  12. package/dist/errors-DsUSZ9m8.js +0 -2605
  13. package/dist/errors-DsUSZ9m8.js.map +0 -1
  14. package/dist/hooks-rXIjX2-H.js +0 -74
  15. package/dist/hooks-rXIjX2-H.js.map +0 -1
  16. package/dist/hooks.js.map +0 -1
  17. package/dist/index.js.map +0 -1
  18. package/dist/migration-support.js.map +0 -1
  19. package/dist/schema-provider-B6-5uzxP.js +0 -2229
  20. package/dist/schema-provider-B6-5uzxP.js.map +0 -1
  21. package/unstable-preview-types/-private/attr.d.ts +0 -167
  22. package/unstable-preview-types/-private/attr.d.ts.map +0 -1
  23. package/unstable-preview-types/-private/attr.type-test.d.ts +0 -4
  24. package/unstable-preview-types/-private/attr.type-test.d.ts.map +0 -1
  25. package/unstable-preview-types/-private/belongs-to.d.ts +0 -175
  26. package/unstable-preview-types/-private/belongs-to.d.ts.map +0 -1
  27. package/unstable-preview-types/-private/belongs-to.type-test.d.ts +0 -4
  28. package/unstable-preview-types/-private/belongs-to.type-test.d.ts.map +0 -1
  29. package/unstable-preview-types/-private/debug/assert-polymorphic-type.d.ts +0 -8
  30. package/unstable-preview-types/-private/debug/assert-polymorphic-type.d.ts.map +0 -1
  31. package/unstable-preview-types/-private/errors.d.ts +0 -292
  32. package/unstable-preview-types/-private/errors.d.ts.map +0 -1
  33. package/unstable-preview-types/-private/has-many.d.ts +0 -166
  34. package/unstable-preview-types/-private/has-many.d.ts.map +0 -1
  35. package/unstable-preview-types/-private/has-many.type-test.d.ts +0 -4
  36. package/unstable-preview-types/-private/has-many.type-test.d.ts.map +0 -1
  37. package/unstable-preview-types/-private/hooks.d.ts +0 -13
  38. package/unstable-preview-types/-private/hooks.d.ts.map +0 -1
  39. package/unstable-preview-types/-private/legacy-relationships-support.d.ts +0 -60
  40. package/unstable-preview-types/-private/legacy-relationships-support.d.ts.map +0 -1
  41. package/unstable-preview-types/-private/model-for-mixin.d.ts +0 -6
  42. package/unstable-preview-types/-private/model-for-mixin.d.ts.map +0 -1
  43. package/unstable-preview-types/-private/model-methods.d.ts +0 -37
  44. package/unstable-preview-types/-private/model-methods.d.ts.map +0 -1
  45. package/unstable-preview-types/-private/model.d.ts +0 -1272
  46. package/unstable-preview-types/-private/model.d.ts.map +0 -1
  47. package/unstable-preview-types/-private/model.type-test.d.ts +0 -4
  48. package/unstable-preview-types/-private/model.type-test.d.ts.map +0 -1
  49. package/unstable-preview-types/-private/notify-changes.d.ts +0 -8
  50. package/unstable-preview-types/-private/notify-changes.d.ts.map +0 -1
  51. package/unstable-preview-types/-private/promise-belongs-to.d.ts +0 -42
  52. package/unstable-preview-types/-private/promise-belongs-to.d.ts.map +0 -1
  53. package/unstable-preview-types/-private/promise-many-array.d.ts +0 -128
  54. package/unstable-preview-types/-private/promise-many-array.d.ts.map +0 -1
  55. package/unstable-preview-types/-private/promise-proxy-base.d.ts +0 -5
  56. package/unstable-preview-types/-private/promise-proxy-base.d.ts.map +0 -1
  57. package/unstable-preview-types/-private/record-state.d.ts +0 -80
  58. package/unstable-preview-types/-private/record-state.d.ts.map +0 -1
  59. package/unstable-preview-types/-private/references/belongs-to.d.ts +0 -497
  60. package/unstable-preview-types/-private/references/belongs-to.d.ts.map +0 -1
  61. package/unstable-preview-types/-private/references/has-many.d.ts +0 -506
  62. package/unstable-preview-types/-private/references/has-many.d.ts.map +0 -1
  63. package/unstable-preview-types/-private/schema-provider.d.ts +0 -65
  64. package/unstable-preview-types/-private/schema-provider.d.ts.map +0 -1
  65. package/unstable-preview-types/-private/type-utils.d.ts +0 -59
  66. package/unstable-preview-types/-private/type-utils.d.ts.map +0 -1
  67. package/unstable-preview-types/-private/util.d.ts +0 -8
  68. package/unstable-preview-types/-private/util.d.ts.map +0 -1
  69. package/unstable-preview-types/-private.d.ts.map +0 -1
  70. package/unstable-preview-types/hooks.d.ts.map +0 -1
  71. package/unstable-preview-types/index.d.ts.map +0 -1
  72. package/unstable-preview-types/migration-support.d.ts.map +0 -1
  73. package/unstable-preview-types/migration-support.type-test.d.ts +0 -4
  74. package/unstable-preview-types/migration-support.type-test.d.ts.map +0 -1
@@ -1,2605 +0,0 @@
1
- import { macroCondition, getGlobalConfig, dependencySatisfies, importSync } from '@embroider/macros';
2
- import { upgradeStore } from '@ember-data/legacy-compat/-private';
3
- import { memoized, defineSignal, defineNonEnumerableSignal, isStableIdentifier, recordIdentifierFor, storeFor, peekCache, SOURCE, fastPush, RelatedCollection, notifyInternalSignal, ARRAY_SIGNAL } from '@ember-data/store/-private';
4
- import { getOrSetGlobal } from '@warp-drive/core-types/-private';
5
- import { EnableHydration } from '@warp-drive/core-types/request';
6
- import { computed, get } from '@ember/object';
7
- import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
8
- import ObjectProxy from '@ember/object/proxy';
9
- import { A } from '@ember/array';
10
- import ArrayProxy from '@ember/array/proxy';
11
- import { mapBy, not } from '@ember/object/computed';
12
- const PromiseObject = ObjectProxy.extend(PromiseProxyMixin);
13
- const deferred = /* @__PURE__ */new WeakMap();
14
- function deferDecorator(proto, prop, desc) {
15
- let map = deferred.get(proto);
16
- if (!map) {
17
- map = /* @__PURE__ */new Map();
18
- deferred.set(proto, map);
19
- }
20
- map.set(prop, desc);
21
- }
22
- function findDeferredDecorator(target, prop) {
23
- var _a;
24
- let cursor = target.prototype;
25
- while (cursor) {
26
- let desc = (_a = deferred.get(cursor)) == null ? void 0 : _a.get(prop);
27
- if (desc) {
28
- return desc;
29
- }
30
- cursor = cursor.prototype;
31
- }
32
- }
33
- function decorateFieldV2(prototype, prop, decorators, initializer) {
34
- let desc = {
35
- configurable: true,
36
- enumerable: true,
37
- writable: true,
38
- initializer: null
39
- };
40
- if (initializer) {
41
- desc.initializer = initializer;
42
- }
43
- for (let decorator of decorators) {
44
- desc = decorator(prototype, prop, desc) || desc;
45
- }
46
- if (desc.initializer === void 0) {
47
- Object.defineProperty(prototype, prop, desc);
48
- } else {
49
- deferDecorator(prototype, prop, desc);
50
- }
51
- }
52
- function decorateMethodV2(prototype, prop, decorators) {
53
- const origDesc = Object.getOwnPropertyDescriptor(prototype, prop);
54
- let desc = {
55
- ...origDesc
56
- };
57
- for (let decorator of decorators) {
58
- desc = decorator(prototype, prop, desc) || desc;
59
- }
60
- if (desc.initializer !== void 0) {
61
- desc.value = desc.initializer ? desc.initializer.call(prototype) : void 0;
62
- desc.initializer = void 0;
63
- }
64
- Object.defineProperty(prototype, prop, desc);
65
- }
66
- function initializeDeferredDecorator(target, prop) {
67
- let desc = findDeferredDecorator(target.constructor, prop);
68
- if (desc) {
69
- Object.defineProperty(target, prop, {
70
- enumerable: desc.enumerable,
71
- configurable: desc.configurable,
72
- writable: desc.writable,
73
- value: desc.initializer ? desc.initializer.call(target) : void 0
74
- });
75
- }
76
- }
77
- const LegacyPromiseProxy = Symbol.for('LegacyPromiseProxy');
78
-
79
- // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-extraneous-class
80
-
81
- const Extended = PromiseObject;
82
-
83
- /**
84
- A PromiseBelongsTo is a PromiseObject that also proxies certain method calls
85
- to the underlying belongsTo model.
86
- Right now we proxy:
87
- * `reload()`
88
- @class PromiseBelongsTo
89
- @private
90
- */
91
- class PromiseBelongsTo extends Extended {
92
- get id() {
93
- const {
94
- key,
95
- legacySupport
96
- } = this._belongsToState;
97
- const ref = legacySupport.referenceFor('belongsTo', key);
98
- return ref.id();
99
- }
100
-
101
- // we don't proxy meta because we would need to proxy it to the relationship state container
102
- // however, meta on relationships does not trigger change notifications.
103
- // if you need relationship meta, you should do `record.belongsTo(relationshipName).meta()`
104
- static {
105
- decorateMethodV2(this.prototype, "id", [memoized]);
106
- }
107
- get meta() {
108
- // eslint-disable-next-line no-constant-condition
109
- {
110
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
111
- {
112
- throw new Error('You attempted to access meta on the promise for the async belongsTo relationship ' + `${this._belongsToState.modelName}:${this._belongsToState.key}'.` + '\nUse `record.belongsTo(relationshipName).meta()` instead.');
113
- }
114
- })() : {};
115
- }
116
- return;
117
- }
118
- static {
119
- decorateMethodV2(this.prototype, "meta", [computed()]);
120
- }
121
- async reload(options) {
122
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
123
- if (!test) {
124
- throw new Error('You are trying to reload an async belongsTo before it has been created');
125
- }
126
- })(this.content !== undefined) : {};
127
- const {
128
- key,
129
- legacySupport
130
- } = this._belongsToState;
131
- await legacySupport.reloadBelongsTo(key, options);
132
- return this;
133
- }
134
- [LegacyPromiseProxy] = true;
135
- }
136
-
137
- /**
138
- This class is returned as the result of accessing an async hasMany relationship
139
- on an instance of a Model extending from `@ember-data/model`.
140
-
141
- A PromiseManyArray is an iterable proxy that allows templates to consume related
142
- ManyArrays and update once their contents are no longer pending.
143
-
144
- In your JS code you should resolve the promise first.
145
-
146
- ```js
147
- const comments = await post.comments;
148
- ```
149
-
150
- @class PromiseManyArray
151
- @public
152
- */
153
- class PromiseManyArray {
154
- constructor(promise, content) {
155
- this._update(promise, content);
156
- this.isDestroyed = false;
157
- }
158
-
159
- /**
160
- * Retrieve the length of the content
161
- * @property length
162
- * @public
163
- */
164
- get length() {
165
- // shouldn't be needed, but ends up being needed
166
- // for computed chains even in 4.x
167
- if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_COMPUTED_CHAINS)) {
168
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
169
- this['[]'];
170
- }
171
- return this.content ? this.content.length : 0;
172
- }
173
-
174
- // this will error if someone tries to call
175
- // A(identifierArray) since it is not configurable
176
- // which is preferrable to the `meta` override we used
177
- // before which required importing all of Ember
178
- static {
179
- decorateMethodV2(this.prototype, "length", [memoized]);
180
- }
181
- get '[]'() {
182
- // ember-source < 3.23 (e.g. 3.20 lts)
183
- // requires that the tag `'[]'` be notified
184
- // on the ArrayProxy in order for `{{#each}}`
185
- // to recompute. We entangle content.
186
- return this.content?.length && this.content;
187
- }
188
-
189
- /**
190
- * Iterate the proxied content. Called by the glimmer iterator in #each
191
- * We do not guarantee that forEach will always be available. This
192
- * may eventually be made to use Symbol.Iterator once glimmer supports it.
193
- *
194
- * @param cb
195
- * @return
196
- * @private
197
- */
198
- static {
199
- decorateMethodV2(this.prototype, '[]', [memoized]);
200
- }
201
- forEach(cb) {
202
- if (this.content && this.length) {
203
- this.content.forEach(cb);
204
- }
205
- }
206
-
207
- /**
208
- * Reload the relationship
209
- * @public
210
- * @param options
211
- * @return
212
- */
213
- reload(options) {
214
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
215
- if (!test) {
216
- throw new Error('You are trying to reload an async manyArray before it has been created');
217
- }
218
- })(this.content) : {};
219
- void this.content.reload(options);
220
- return this;
221
- }
222
-
223
- //---- Properties/Methods from the PromiseProxyMixin that we will keep as our API
224
-
225
- /**
226
- * Whether the loading promise is still pending
227
- *
228
- * @property isPending
229
- * @type {Boolean}
230
- * @public
231
- */
232
-
233
- /**
234
- * Whether the loading promise rejected
235
- *
236
- * @property isRejected
237
- * @type {Boolean}
238
- * @public
239
- */
240
-
241
- /**
242
- * Whether the loading promise succeeded
243
- *
244
- * @property isFulfilled
245
- * @type {Boolean}
246
- * @public
247
- */
248
-
249
- /**
250
- * Whether the loading promise completed (resolved or rejected)
251
- *
252
- * @property isSettled
253
- * @type {Boolean}
254
- * @public
255
- */
256
-
257
- /**
258
- * chain this promise
259
- *
260
- * @public
261
- * @param success
262
- * @param fail
263
- * @return {Promise}
264
- */
265
- then(s, f) {
266
- return this.promise.then(s, f);
267
- }
268
-
269
- /**
270
- * catch errors thrown by this promise
271
- * @public
272
- * @param callback
273
- * @return {Promise}
274
- */
275
- catch(cb) {
276
- return this.promise.catch(cb);
277
- }
278
-
279
- /**
280
- * run cleanup after this promise completes
281
- *
282
- * @public
283
- * @param callback
284
- * @return {Promise}
285
- */
286
- finally(cb) {
287
- return this.promise.finally(cb);
288
- }
289
-
290
- //---- Methods on EmberObject that we should keep
291
-
292
- destroy() {
293
- this.isDestroyed = true;
294
- this.content = null;
295
- this.promise = null;
296
- }
297
-
298
- //---- Methods/Properties on ManyArray that we own and proxy to
299
-
300
- /**
301
- * Retrieve the links for this relationship
302
- * @property links
303
- * @public
304
- */
305
- get links() {
306
- return this.content ? this.content.links : undefined;
307
- }
308
-
309
- /**
310
- * Retrieve the meta for this relationship
311
- * @property meta
312
- * @public
313
- */
314
- static {
315
- decorateMethodV2(this.prototype, "links", [memoized]);
316
- }
317
- get meta() {
318
- return this.content ? this.content.meta : undefined;
319
- }
320
-
321
- //---- Our own stuff
322
- static {
323
- decorateMethodV2(this.prototype, "meta", [memoized]);
324
- }
325
- _update(promise, content) {
326
- if (content !== undefined) {
327
- this.content = content;
328
- }
329
- this.promise = tapPromise(this, promise);
330
- }
331
- static create({
332
- promise,
333
- content
334
- }) {
335
- return new this(promise, content);
336
- }
337
- [LegacyPromiseProxy] = true;
338
- }
339
- defineSignal(PromiseManyArray.prototype, 'content', null);
340
- defineSignal(PromiseManyArray.prototype, 'isPending', false);
341
- defineSignal(PromiseManyArray.prototype, 'isRejected', false);
342
- defineSignal(PromiseManyArray.prototype, 'isFulfilled', false);
343
- defineSignal(PromiseManyArray.prototype, 'isSettled', false);
344
- function tapPromise(proxy, promise) {
345
- proxy.isPending = true;
346
- proxy.isSettled = false;
347
- proxy.isFulfilled = false;
348
- proxy.isRejected = false;
349
- return Promise.resolve(promise).then(content => {
350
- proxy.isPending = false;
351
- proxy.isFulfilled = true;
352
- proxy.isSettled = true;
353
- proxy.content = content;
354
- return content;
355
- }, error => {
356
- proxy.isPending = false;
357
- proxy.isFulfilled = false;
358
- proxy.isRejected = true;
359
- proxy.isSettled = true;
360
- throw error;
361
- });
362
- }
363
-
364
- /*
365
- Assert that `addedRecord` has a valid type so it can be added to the
366
- relationship of the `record`.
367
-
368
- The assert basically checks if the `addedRecord` can be added to the
369
- relationship (specified via `relationshipMeta`) of the `record`.
370
-
371
- This utility should only be used internally, as both record parameters must
372
- be stable record identifiers and the `relationshipMeta` needs to be the meta
373
- information about the relationship, retrieved via
374
- `record.relationshipFor(key)`.
375
- */
376
- let assertPolymorphicType;
377
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
378
- // eslint-disable-next-line @typescript-eslint/no-shadow
379
- assertPolymorphicType = function assertPolymorphicType(parentIdentifier, parentDefinition, addedIdentifier, store) {
380
- if (parentDefinition.inverseIsImplicit) {
381
- return;
382
- }
383
- if (parentDefinition.isPolymorphic) {
384
- const meta = store.schema.fields(addedIdentifier)?.get(parentDefinition.inverseKey);
385
- if (meta) {
386
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
387
- if (!test) {
388
- throw new Error(`Expected the schema for the field ${parentDefinition.inverseKey} on ${addedIdentifier.type} to be for a legacy relationship`);
389
- }
390
- })(meta.kind === 'belongsTo' || meta.kind === 'hasMany') : {};
391
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
392
- if (!test) {
393
- throw new Error(`The schema for the relationship '${parentDefinition.inverseKey}' on '${addedIdentifier.type}' type does not implement '${parentDefinition.type}' and thus cannot be assigned to the '${parentDefinition.key}' relationship in '${parentIdentifier.type}'. The definition should specify 'as: "${parentDefinition.type}"' in options.`);
394
- }
395
- })(meta?.options?.as === parentDefinition.type) : {};
396
- }
397
- }
398
- };
399
- }
400
- function isResourceIdentiferWithRelatedLinks$1(value) {
401
- return Boolean(value && value.links && value.links.related);
402
- }
403
- /**
404
- A `HasManyReference` is a low-level API that allows access
405
- and manipulation of a hasMany relationship.
406
-
407
- It is especially useful when you're dealing with `async` relationships
408
- from `@ember-data/model` as it allows synchronous access to
409
- the relationship data if loaded, as well as APIs for loading, reloading
410
- the data or accessing available information without triggering a load.
411
-
412
- It may also be useful when using `sync` relationships with `@ember-data/model`
413
- that need to be loaded/reloaded with more precise timing than marking the
414
- relationship as `async` and relying on autofetch would have allowed.
415
-
416
- However,keep in mind that marking a relationship as `async: false` will introduce
417
- bugs into your application if the data is not always guaranteed to be available
418
- by the time the relationship is accessed. Ergo, it is recommended when using this
419
- approach to utilize `links` for unloaded relationship state instead of identifiers.
420
-
421
- Reference APIs are entangled with the relationship's underlying state,
422
- thus any getters or cached properties that utilize these will properly
423
- invalidate if the relationship state changes.
424
-
425
- References are "stable", meaning that multiple calls to retrieve the reference
426
- for a given relationship will always return the same HasManyReference.
427
-
428
- @class HasManyReference
429
- @public
430
- */
431
- class HasManyReference {
432
- /**
433
- * The field name on the parent record for this has-many relationship.
434
- *
435
- * @property key
436
- * @type {String}
437
- * @public
438
- */
439
-
440
- /**
441
- * The type of resource this relationship will contain.
442
- *
443
- * @property type
444
- * @type {String}
445
- * @public
446
- */
447
-
448
- // unsubscribe tokens given to us by the notification manager
449
- ___token;
450
- ___identifier;
451
- ___relatedTokenMap;
452
- constructor(store, graph, parentIdentifier, hasManyRelationship, key) {
453
- this.graph = graph;
454
- this.key = key;
455
- this.hasManyRelationship = hasManyRelationship;
456
- this.type = hasManyRelationship.definition.type;
457
- this.store = store;
458
- this.___identifier = parentIdentifier;
459
- this.___token = store.notifications.subscribe(parentIdentifier, (_, bucket, notifiedKey) => {
460
- if (bucket === 'relationships' && notifiedKey === key) {
461
- this._ref++;
462
- }
463
- });
464
- this.___relatedTokenMap = new Map();
465
- // TODO inverse
466
- }
467
-
468
- /**
469
- * This method should never be called by user code.
470
- *
471
- * @internal
472
- */
473
- destroy() {
474
- this.store.notifications.unsubscribe(this.___token);
475
- this.___relatedTokenMap.forEach(token => {
476
- this.store.notifications.unsubscribe(token);
477
- });
478
- this.___relatedTokenMap.clear();
479
- }
480
-
481
- /**
482
- * An array of identifiers for the records that this reference refers to.
483
- *
484
- * @property identifiers
485
- * @type {StableRecordIdentifier[]}
486
- * @public
487
- */
488
- get identifiers() {
489
- ensureRefCanSubscribe(this);
490
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
491
- this._ref;
492
- const resource = this._resource();
493
- const map = this.___relatedTokenMap;
494
- this.___relatedTokenMap = new Map();
495
- if (resource && resource.data) {
496
- return resource.data.map(resourceIdentifier => {
497
- const identifier = this.store.identifierCache.getOrCreateRecordIdentifier(resourceIdentifier);
498
- let token = map.get(identifier);
499
- if (token) {
500
- map.delete(identifier);
501
- } else {
502
- token = this.store.notifications.subscribe(identifier, (_, bucket, notifiedKey) => {
503
- if (bucket === 'identity' || bucket === 'attributes' && notifiedKey === 'id') {
504
- this._ref++;
505
- }
506
- });
507
- }
508
- this.___relatedTokenMap.set(identifier, token);
509
- return identifier;
510
- });
511
- }
512
- map.forEach(token => {
513
- this.store.notifications.unsubscribe(token);
514
- });
515
- map.clear();
516
- return [];
517
- }
518
- static {
519
- decorateMethodV2(this.prototype, "identifiers", [memoized]);
520
- }
521
- _resource() {
522
- const cache = this.store.cache;
523
- return cache.getRelationship(this.___identifier, this.key);
524
- }
525
-
526
- /**
527
- This returns a string that represents how the reference will be
528
- looked up when it is loaded. If the relationship has a link it will
529
- use the "link" otherwise it defaults to "id".
530
- Example
531
- ```js [app/models/post.js]
532
- import Model, { hasMany } from '@ember-data/model';
533
- export default class PostModel extends Model {
534
- @hasMany('comment', { async: true, inverse: null }) comments;
535
- }
536
- ```
537
- ```javascript
538
- let post = store.push({
539
- data: {
540
- type: 'post',
541
- id: 1,
542
- relationships: {
543
- comments: {
544
- data: [{ type: 'comment', id: 1 }]
545
- }
546
- }
547
- }
548
- });
549
- let commentsRef = post.hasMany('comments');
550
- // get the identifier of the reference
551
- if (commentsRef.remoteType() === "ids") {
552
- let ids = commentsRef.ids();
553
- } else if (commentsRef.remoteType() === "link") {
554
- let link = commentsRef.link();
555
- }
556
- ```
557
- @public
558
- @return {String} The name of the remote type. This should either be `link` or `ids`
559
- */
560
- remoteType() {
561
- const value = this._resource();
562
- if (value && value.links && value.links.related) {
563
- return 'link';
564
- }
565
- return 'ids';
566
- }
567
-
568
- /**
569
- `ids()` returns an array of the record IDs in this relationship.
570
- Example
571
- ```js [app/models/post.js]
572
- import Model, { hasMany } from '@ember-data/model';
573
- export default class PostModel extends Model {
574
- @hasMany('comment', { async: true, inverse: null }) comments;
575
- }
576
- ```
577
- ```javascript
578
- let post = store.push({
579
- data: {
580
- type: 'post',
581
- id: 1,
582
- relationships: {
583
- comments: {
584
- data: [{ type: 'comment', id: 1 }]
585
- }
586
- }
587
- }
588
- });
589
- let commentsRef = post.hasMany('comments');
590
- commentsRef.ids(); // ['1']
591
- ```
592
- @public
593
- @return {Array} The ids in this has-many relationship
594
- */
595
- ids() {
596
- return this.identifiers.map(identifier => identifier.id);
597
- }
598
-
599
- /**
600
- The link Ember Data will use to fetch or reload this belongs-to
601
- relationship. By default it uses only the "related" resource linkage.
602
- Example
603
- ```javascript
604
- // models/blog.js
605
- import Model, { belongsTo } from '@ember-data/model';
606
- export default Model.extend({
607
- user: belongsTo('user', { async: true, inverse: null })
608
- });
609
- let blog = store.push({
610
- data: {
611
- type: 'blog',
612
- id: 1,
613
- relationships: {
614
- user: {
615
- links: {
616
- related: '/articles/1/author'
617
- }
618
- }
619
- }
620
- }
621
- });
622
- let userRef = blog.belongsTo('user');
623
- // get the identifier of the reference
624
- if (userRef.remoteType() === "link") {
625
- let link = userRef.link();
626
- }
627
- ```
628
- @public
629
- @return {String} The link Ember Data will use to fetch or reload this belongs-to relationship.
630
- */
631
- link() {
632
- const resource = this._resource();
633
- if (isResourceIdentiferWithRelatedLinks$1(resource)) {
634
- if (resource.links) {
635
- const related = resource.links.related;
636
- return !related || typeof related === 'string' ? related : related.href;
637
- }
638
- }
639
- return null;
640
- }
641
-
642
- /**
643
- * any links that have been received for this relationship
644
- *
645
- * @public
646
- * @return
647
- */
648
- links() {
649
- const resource = this._resource();
650
- return resource && resource.links ? resource.links : null;
651
- }
652
-
653
- /**
654
- The meta data for the has-many relationship.
655
- Example
656
- ```javascript
657
- // models/blog.js
658
- import Model, { hasMany } from '@ember-data/model';
659
- export default Model.extend({
660
- users: hasMany('user', { async: true, inverse: null })
661
- });
662
- let blog = store.push({
663
- data: {
664
- type: 'blog',
665
- id: 1,
666
- relationships: {
667
- users: {
668
- links: {
669
- related: {
670
- href: '/articles/1/authors'
671
- },
672
- },
673
- meta: {
674
- lastUpdated: 1458014400000
675
- }
676
- }
677
- }
678
- }
679
- });
680
- let usersRef = blog.hasMany('user');
681
- usersRef.meta() // { lastUpdated: 1458014400000 }
682
- ```
683
- @public
684
- @return {Object|null} The meta information for the belongs-to relationship.
685
- */
686
- meta() {
687
- let meta = null;
688
- const resource = this._resource();
689
- if (resource && resource.meta && typeof resource.meta === 'object') {
690
- meta = resource.meta;
691
- }
692
- return meta;
693
- }
694
-
695
- /**
696
- `push` can be used to update the data in the relationship and EmberData
697
- will treat the new data as the canonical value of this relationship on
698
- the backend. An empty array will signify the canonical value should be
699
- empty.
700
- Example model
701
- ```js [app/models/post.js]
702
- import Model, { hasMany } from '@ember-data/model';
703
- export default class PostModel extends Model {
704
- @hasMany('comment', { async: true, inverse: null }) comments;
705
- }
706
- ```
707
- Setup some initial state, note we haven't loaded the comments yet:
708
- ```js
709
- const post = store.push({
710
- data: {
711
- type: 'post',
712
- id: '1',
713
- relationships: {
714
- comments: {
715
- data: [{ type: 'comment', id: '1' }]
716
- }
717
- }
718
- }
719
- });
720
- const commentsRef = post.hasMany('comments');
721
- commentsRef.ids(); // ['1']
722
- ```
723
- Update the state using `push`, note we can do this even without
724
- having loaded these comments yet by providing resource identifiers.
725
- Both full resources and resource identifiers are supported.
726
- ```js
727
- await commentsRef.push({
728
- data: [
729
- { type: 'comment', id: '2' },
730
- { type: 'comment', id: '3' },
731
- ]
732
- });
733
- commentsRef.ids(); // ['2', '3']
734
- ```
735
- For convenience, you can also pass in an array of resources or resource identifiers
736
- without wrapping them in the `data` property:
737
- ```js
738
- await commentsRef.push([
739
- { type: 'comment', id: '4' },
740
- { type: 'comment', id: '5' },
741
- ]);
742
- commentsRef.ids(); // ['4', '5']
743
- ```
744
- When using the `data` property, you may also include other resource data via included,
745
- as well as provide new links and meta to the relationship.
746
- ```js
747
- await commentsRef.push({
748
- links: {
749
- related: '/posts/1/comments'
750
- },
751
- meta: {
752
- total: 2
753
- },
754
- data: [
755
- { type: 'comment', id: '4' },
756
- { type: 'comment', id: '5' },
757
- ],
758
- included: [
759
- { type: 'other-thing', id: '1', attributes: { foo: 'bar' },
760
- ]
761
- });
762
- ```
763
- By default, the store will attempt to fetch any unloaded records before resolving
764
- the returned promise with the ManyArray.
765
- Alternatively, pass `true` as the second argument to avoid fetching unloaded records
766
- and instead the promise will resolve with void without attempting to fetch. This is
767
- particularly useful if you want to update the state of the relationship without
768
- forcing the load of all of the associated records.
769
- @public
770
- @param {Array|Object} doc a JSONAPI document object describing the new value of this relationship.
771
- @param {Boolean} [skipFetch] if `true`, do not attempt to fetch unloaded records
772
- @return {Promise<ManyArray | void>}
773
- */
774
- async push(doc, skipFetch) {
775
- const {
776
- store
777
- } = this;
778
- const dataDoc = Array.isArray(doc) ? {
779
- data: doc
780
- } : doc;
781
- const isResourceData = Array.isArray(dataDoc.data) && dataDoc.data.length > 0 && isMaybeResource(dataDoc.data[0]);
782
-
783
- // enforce that one of links, meta or data is present
784
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
785
- if (!test) {
786
- throw new Error(`You must provide at least one of 'links', 'meta' or 'data' when calling hasManyReference.push`);
787
- }
788
- })('links' in dataDoc || 'meta' in dataDoc || 'data' in dataDoc) : {};
789
- const identifiers = !Array.isArray(dataDoc.data) ? [] : isResourceData ? store._push(dataDoc, true) : dataDoc.data.map(i => store.identifierCache.getOrCreateRecordIdentifier(i));
790
- const {
791
- identifier
792
- } = this.hasManyRelationship;
793
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
794
- const relationshipMeta = this.hasManyRelationship.definition;
795
- identifiers.forEach(added => {
796
- assertPolymorphicType(identifier, relationshipMeta, added, store);
797
- });
798
- }
799
- const newData = {};
800
- // only set data if it was passed in
801
- if (Array.isArray(dataDoc.data)) {
802
- newData.data = identifiers;
803
- }
804
- if ('links' in dataDoc) {
805
- newData.links = dataDoc.links;
806
- }
807
- if ('meta' in dataDoc) {
808
- newData.meta = dataDoc.meta;
809
- }
810
- store._join(() => {
811
- this.graph.push({
812
- op: 'updateRelationship',
813
- record: identifier,
814
- field: this.key,
815
- value: newData
816
- });
817
- });
818
- if (!skipFetch) return this.load();
819
- }
820
- _isLoaded() {
821
- const hasRelationshipDataProperty = this.hasManyRelationship.state.hasReceivedData;
822
- if (!hasRelationshipDataProperty) {
823
- return false;
824
- }
825
- const relationship = this.graph.getData(this.hasManyRelationship.identifier, this.key);
826
- return relationship.data?.every(identifier => {
827
- return this.store._instanceCache.recordIsLoaded(identifier, true) === true;
828
- });
829
- }
830
-
831
- /**
832
- `value()` synchronously returns the current value of the has-many
833
- relationship. Unlike `record.relationshipName`, calling
834
- `value()` on a reference does not trigger a fetch if the async
835
- relationship is not yet loaded. If the relationship is not loaded
836
- it will always return `null`.
837
- Example
838
- ```js [app/models/post.js]
839
- import Model, { hasMany } from '@ember-data/model';
840
- export default class PostModel extends Model {
841
- @hasMany('comment', { async: true, inverse: null }) comments;
842
- }
843
- ```
844
- ```javascript
845
- let post = store.push({
846
- data: {
847
- type: 'post',
848
- id: 1,
849
- relationships: {
850
- comments: {
851
- data: [{ type: 'comment', id: 1 }]
852
- }
853
- }
854
- }
855
- });
856
- let commentsRef = post.hasMany('comments');
857
- post.comments.then(function(comments) {
858
- commentsRef.value() === comments
859
- })
860
- ```
861
- @public
862
- @return {ManyArray}
863
- */
864
- value() {
865
- const support = LEGACY_SUPPORT.get(this.___identifier);
866
- if (!ensureRefCanSubscribe(this)) {
867
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
868
- this._ref;
869
- return null;
870
- }
871
- return support.getManyArray(this.key);
872
- }
873
-
874
- /**
875
- Loads the relationship if it is not already loaded. If the
876
- relationship is already loaded this method does not trigger a new
877
- load. This causes a request to the specified
878
- relationship link or reloads all items currently in the relationship.
879
- Example
880
- ```js [app/models/post.js]
881
- import Model, { hasMany } from '@ember-data/model';
882
- export default class PostModel extends Model {
883
- @hasMany('comment', { async: true, inverse: null }) comments;
884
- }
885
- ```
886
- ```javascript
887
- let post = store.push({
888
- data: {
889
- type: 'post',
890
- id: 1,
891
- relationships: {
892
- comments: {
893
- data: [{ type: 'comment', id: 1 }]
894
- }
895
- }
896
- }
897
- });
898
- let commentsRef = post.hasMany('comments');
899
- commentsRef.load().then(function(comments) {
900
- //...
901
- });
902
- ```
903
- You may also pass in an options object whose properties will be
904
- fed forward. This enables you to pass `adapterOptions` into the
905
- request given to the adapter via the reference.
906
- Example
907
- ```javascript
908
- commentsRef.load({ adapterOptions: { isPrivate: true } })
909
- .then(function(comments) {
910
- //...
911
- });
912
- ```
913
- ```js [app/adapters/comment.js]
914
- export default ApplicationAdapter.extend({
915
- findMany(store, type, id, snapshots) {
916
- // In the adapter you will have access to adapterOptions.
917
- let adapterOptions = snapshots[0].adapterOptions;
918
- }
919
- });
920
- ```
921
- @public
922
- @param {Object} options the options to pass in.
923
- @return {Promise} a promise that resolves with the ManyArray in
924
- this has-many relationship.
925
- */
926
- async load(options) {
927
- const support = LEGACY_SUPPORT.get(this.___identifier);
928
- const fetchSyncRel = !this.hasManyRelationship.definition.isAsync && !areAllInverseRecordsLoaded(this.store, this._resource());
929
- return fetchSyncRel ? support.reloadHasMany(this.key, options) :
930
- // we cast to fix the return type since typescript and eslint don't understand async functions
931
- // properly
932
- support.getHasMany(this.key, options);
933
- }
934
-
935
- /**
936
- Reloads this has-many relationship. This causes a request to the specified
937
- relationship link or reloads all items currently in the relationship.
938
- Example
939
- ```js [app/models/post.js]
940
- import Model, { hasMany } from '@ember-data/model';
941
- export default class PostModel extends Model {
942
- @hasMany('comment', { async: true, inverse: null }) comments;
943
- }
944
- ```
945
- ```javascript
946
- let post = store.push({
947
- data: {
948
- type: 'post',
949
- id: 1,
950
- relationships: {
951
- comments: {
952
- data: [{ type: 'comment', id: 1 }]
953
- }
954
- }
955
- }
956
- });
957
- let commentsRef = post.hasMany('comments');
958
- commentsRef.reload().then(function(comments) {
959
- //...
960
- });
961
- ```
962
- You may also pass in an options object whose properties will be
963
- fed forward. This enables you to pass `adapterOptions` into the
964
- request given to the adapter via the reference. A full example
965
- can be found in the `load` method.
966
- Example
967
- ```javascript
968
- commentsRef.reload({ adapterOptions: { isPrivate: true } })
969
- ```
970
- @public
971
- @param {Object} options the options to pass in.
972
- @return {Promise} a promise that resolves with the ManyArray in this has-many relationship.
973
- */
974
- reload(options) {
975
- const support = LEGACY_SUPPORT.get(this.___identifier);
976
- return support.reloadHasMany(this.key, options);
977
- }
978
- }
979
- defineNonEnumerableSignal(HasManyReference.prototype, '_ref', 0);
980
- function isMaybeResource(object) {
981
- const keys = Object.keys(object).filter(k => k !== 'id' && k !== 'type' && k !== 'lid');
982
- return keys.length > 0;
983
- }
984
- function ensureRefCanSubscribe(rel) {
985
- const loaded = rel._isLoaded();
986
- if (!loaded) {
987
- // subscribe to changes
988
- // for when we are not loaded yet
989
- //
990
- // because the graph optimizes the case where a relationship has never been subscribed,
991
- // we force accessed to be true here. When we make the graph public we should create a
992
- // subscribe/unsubscribe API
993
- const edge = rel.graph.get(rel.___identifier, rel.key);
994
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
995
- if (!test) {
996
- throw new Error(`Expected a hasMany relationship for ${rel.___identifier.type}:${rel.key}`);
997
- }
998
- })('accessed' in edge) : {};
999
- edge.accessed = true;
1000
- return false;
1001
- }
1002
- return true;
1003
- }
1004
- function isResourceIdentiferWithRelatedLinks(value) {
1005
- return Boolean(value && value.links && value.links.related);
1006
- }
1007
-
1008
- /**
1009
- A `BelongsToReference` is a low-level API that allows access
1010
- and manipulation of a belongsTo relationship.
1011
-
1012
- It is especially useful when you're dealing with `async` relationships
1013
- from `@ember-data/model` as it allows synchronous access to
1014
- the relationship data if loaded, as well as APIs for loading, reloading
1015
- the data or accessing available information without triggering a load.
1016
-
1017
- It may also be useful when using `sync` relationships with `@ember-data/model`
1018
- that need to be loaded/reloaded with more precise timing than marking the
1019
- relationship as `async` and relying on autofetch would have allowed.
1020
-
1021
- However,keep in mind that marking a relationship as `async: false` will introduce
1022
- bugs into your application if the data is not always guaranteed to be available
1023
- by the time the relationship is accessed. Ergo, it is recommended when using this
1024
- approach to utilize `links` for unloaded relationship state instead of identifiers.
1025
-
1026
- Reference APIs are entangled with the relationship's underlying state,
1027
- thus any getters or cached properties that utilize these will properly
1028
- invalidate if the relationship state changes.
1029
-
1030
- References are "stable", meaning that multiple calls to retrieve the reference
1031
- for a given relationship will always return the same HasManyReference.
1032
-
1033
- @class BelongsToReference
1034
- @public
1035
- */
1036
- class BelongsToReference {
1037
- /**
1038
- * The field name on the parent record for this has-many relationship.
1039
- *
1040
- * @property key
1041
- * @type {String}
1042
- * @public
1043
- */
1044
-
1045
- /**
1046
- * The type of resource this relationship will contain.
1047
- *
1048
- * @property type
1049
- * @type {String}
1050
- * @public
1051
- */
1052
-
1053
- // unsubscribe tokens given to us by the notification manager
1054
-
1055
- constructor(store, graph, parentIdentifier, belongsToRelationship, key) {
1056
- this.graph = graph;
1057
- this.key = key;
1058
- this.belongsToRelationship = belongsToRelationship;
1059
- this.type = belongsToRelationship.definition.type;
1060
- this.store = store;
1061
- this.___identifier = parentIdentifier;
1062
- this.___relatedToken = null;
1063
- this.___token = store.notifications.subscribe(parentIdentifier, (_, bucket, notifiedKey) => {
1064
- if (bucket === 'relationships' && notifiedKey === key) {
1065
- this._ref++;
1066
- }
1067
- });
1068
-
1069
- // TODO inverse
1070
- }
1071
- destroy() {
1072
- // TODO @feature we need the notification manager often enough
1073
- // we should potentially just expose it fully public
1074
- this.store.notifications.unsubscribe(this.___token);
1075
- this.___token = null;
1076
- if (this.___relatedToken) {
1077
- this.store.notifications.unsubscribe(this.___relatedToken);
1078
- this.___relatedToken = null;
1079
- }
1080
- }
1081
-
1082
- /**
1083
- * The identifier of the record that this reference refers to.
1084
- * `null` if no related record is known.
1085
- *
1086
- * @property identifier
1087
- * @type {StableRecordIdentifier | null}
1088
- * @public
1089
- */
1090
- get identifier() {
1091
- if (this.___relatedToken) {
1092
- this.store.notifications.unsubscribe(this.___relatedToken);
1093
- this.___relatedToken = null;
1094
- }
1095
- const resource = this._resource();
1096
- if (resource && resource.data) {
1097
- const identifier = this.store.identifierCache.getOrCreateRecordIdentifier(resource.data);
1098
- this.___relatedToken = this.store.notifications.subscribe(identifier, (_, bucket, notifiedKey) => {
1099
- if (bucket === 'identity' || bucket === 'attributes' && notifiedKey === 'id') {
1100
- this._ref++;
1101
- }
1102
- });
1103
- return identifier;
1104
- }
1105
- return null;
1106
- }
1107
-
1108
- /**
1109
- The `id` of the record that this reference refers to. Together, the
1110
- `type()` and `id()` methods form a composite key for the identity
1111
- map. This can be used to access the id of an async relationship
1112
- without triggering a fetch that would normally happen if you
1113
- attempted to use `record.relationship.id`.
1114
- Example
1115
- ```javascript
1116
- // models/blog.js
1117
- import Model, { belongsTo } from '@ember-data/model';
1118
- export default class BlogModel extends Model {
1119
- @belongsTo('user', { async: true, inverse: null }) user;
1120
- }
1121
- let blog = store.push({
1122
- data: {
1123
- type: 'blog',
1124
- id: 1,
1125
- relationships: {
1126
- user: {
1127
- data: { type: 'user', id: 1 }
1128
- }
1129
- }
1130
- }
1131
- });
1132
- let userRef = blog.belongsTo('user');
1133
- // get the identifier of the reference
1134
- if (userRef.remoteType() === "id") {
1135
- let id = userRef.id();
1136
- }
1137
- ```
1138
- @public
1139
- @return {String} The id of the record in this belongsTo relationship.
1140
- */
1141
- static {
1142
- decorateMethodV2(this.prototype, "identifier", [memoized]);
1143
- }
1144
- id() {
1145
- return this.identifier?.id || null;
1146
- }
1147
-
1148
- /**
1149
- The link Ember Data will use to fetch or reload this belongs-to
1150
- relationship. By default it uses only the "related" resource linkage.
1151
- Example
1152
- ```javascript
1153
- // models/blog.js
1154
- import Model, { belongsTo } from '@ember-data/model';
1155
- export default Model.extend({
1156
- user: belongsTo('user', { async: true, inverse: null })
1157
- });
1158
- let blog = store.push({
1159
- data: {
1160
- type: 'blog',
1161
- id: 1,
1162
- relationships: {
1163
- user: {
1164
- links: {
1165
- related: '/articles/1/author'
1166
- }
1167
- }
1168
- }
1169
- }
1170
- });
1171
- let userRef = blog.belongsTo('user');
1172
- // get the identifier of the reference
1173
- if (userRef.remoteType() === "link") {
1174
- let link = userRef.link();
1175
- }
1176
- ```
1177
- @public
1178
- @return {String} The link Ember Data will use to fetch or reload this belongs-to relationship.
1179
- */
1180
- link() {
1181
- const resource = this._resource();
1182
- if (isResourceIdentiferWithRelatedLinks(resource)) {
1183
- if (resource.links) {
1184
- const related = resource.links.related;
1185
- return !related || typeof related === 'string' ? related : related.href;
1186
- }
1187
- }
1188
- return null;
1189
- }
1190
-
1191
- /**
1192
- * any links that have been received for this relationship
1193
- *
1194
- * @public
1195
- * @return
1196
- */
1197
- links() {
1198
- const resource = this._resource();
1199
- return resource && resource.links ? resource.links : null;
1200
- }
1201
-
1202
- /**
1203
- The meta data for the belongs-to relationship.
1204
- Example
1205
- ```javascript
1206
- // models/blog.js
1207
- import Model, { belongsTo } from '@ember-data/model';
1208
- export default Model.extend({
1209
- user: belongsTo('user', { async: true, inverse: null })
1210
- });
1211
- let blog = store.push({
1212
- data: {
1213
- type: 'blog',
1214
- id: 1,
1215
- relationships: {
1216
- user: {
1217
- links: {
1218
- related: {
1219
- href: '/articles/1/author'
1220
- },
1221
- },
1222
- meta: {
1223
- lastUpdated: 1458014400000
1224
- }
1225
- }
1226
- }
1227
- }
1228
- });
1229
- let userRef = blog.belongsTo('user');
1230
- userRef.meta() // { lastUpdated: 1458014400000 }
1231
- ```
1232
- @public
1233
- @return {Object} The meta information for the belongs-to relationship.
1234
- */
1235
- meta() {
1236
- let meta = null;
1237
- const resource = this._resource();
1238
- if (resource && resource.meta && typeof resource.meta === 'object') {
1239
- meta = resource.meta;
1240
- }
1241
- return meta;
1242
- }
1243
- _resource() {
1244
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
1245
- this._ref; // subscribe
1246
- const cache = this.store.cache;
1247
- return cache.getRelationship(this.___identifier, this.key);
1248
- }
1249
-
1250
- /**
1251
- This returns a string that represents how the reference will be
1252
- looked up when it is loaded. If the relationship has a link it will
1253
- use the "link" otherwise it defaults to "id".
1254
- Example
1255
- ```js [app/models/post.js]
1256
- import Model, { hasMany } from '@ember-data/model';
1257
- export default class PostModel extends Model {
1258
- @hasMany('comment', { async: true, inverse: null }) comments;
1259
- }
1260
- ```
1261
- ```javascript
1262
- let post = store.push({
1263
- data: {
1264
- type: 'post',
1265
- id: 1,
1266
- relationships: {
1267
- comments: {
1268
- data: [{ type: 'comment', id: 1 }]
1269
- }
1270
- }
1271
- }
1272
- });
1273
- let commentsRef = post.hasMany('comments');
1274
- // get the identifier of the reference
1275
- if (commentsRef.remoteType() === "ids") {
1276
- let ids = commentsRef.ids();
1277
- } else if (commentsRef.remoteType() === "link") {
1278
- let link = commentsRef.link();
1279
- }
1280
- ```
1281
- @public
1282
- @return {String} The name of the remote type. This should either be `link` or `id`
1283
- */
1284
- remoteType() {
1285
- const value = this._resource();
1286
- if (isResourceIdentiferWithRelatedLinks(value)) {
1287
- return 'link';
1288
- }
1289
- return 'id';
1290
- }
1291
-
1292
- /**
1293
- `push` can be used to update the data in the relationship and EmberData
1294
- will treat the new data as the canonical value of this relationship on
1295
- the backend. A value of `null` (e.g. `{ data: null }`) can be passed to
1296
- clear the relationship.
1297
- Example model
1298
- ```js [app/models/blog.js]
1299
- import Model, { belongsTo } from '@ember-data/model';
1300
- export default class BlogModel extends Model {
1301
- @belongsTo('user', { async: true, inverse: null }) user;
1302
- }
1303
- ```
1304
- Setup some initial state, note we haven't loaded the user yet:
1305
- ```js
1306
- const blog = store.push({
1307
- data: {
1308
- type: 'blog',
1309
- id: '1',
1310
- relationships: {
1311
- user: {
1312
- data: { type: 'user', id: '1' }
1313
- }
1314
- }
1315
- }
1316
- });
1317
- const userRef = blog.belongsTo('user');
1318
- userRef.id(); // '1'
1319
- ```
1320
- Update the state using `push`, note we can do this even without
1321
- having loaded the user yet by providing a resource-identifier.
1322
- Both full a resource and a resource-identifier are supported.
1323
- ```js
1324
- await userRef.push({
1325
- data: {
1326
- type: 'user',
1327
- id: '2',
1328
- }
1329
- });
1330
- userRef.id(); // '2'
1331
- ```
1332
- You may also pass in links and meta fore the relationship, and sideload
1333
- additional resources that might be required.
1334
- ```js
1335
- await userRef.push({
1336
- data: {
1337
- type: 'user',
1338
- id: '2',
1339
- },
1340
- links: {
1341
- related: '/articles/1/author'
1342
- },
1343
- meta: {
1344
- lastUpdated: Date.now()
1345
- },
1346
- included: [
1347
- {
1348
- type: 'user-preview',
1349
- id: '2',
1350
- attributes: {
1351
- username: '@runspired'
1352
- }
1353
- }
1354
- ]
1355
- });
1356
- ```
1357
- By default, the store will attempt to fetch the record if it is not loaded or its
1358
- resource data is not included in the call to `push` before resolving the returned
1359
- promise with the new state..
1360
- Alternatively, pass `true` as the second argument to avoid fetching unloaded records
1361
- and instead the promise will resolve with void without attempting to fetch. This is
1362
- particularly useful if you want to update the state of the relationship without
1363
- forcing the load of all of the associated record.
1364
- @public
1365
- @param {Object} doc a JSONAPI document object describing the new value of this relationship.
1366
- @param {Boolean} [skipFetch] if `true`, do not attempt to fetch unloaded records
1367
- @return {Promise<OpaqueRecordInstance | null | void>}
1368
- */
1369
- async push(doc, skipFetch) {
1370
- const {
1371
- store
1372
- } = this;
1373
- const isResourceData = doc.data && isMaybeResource(doc.data);
1374
- const added = isResourceData ? store._push(doc, true) : doc.data ? store.identifierCache.getOrCreateRecordIdentifier(doc.data) : null;
1375
- const {
1376
- identifier
1377
- } = this.belongsToRelationship;
1378
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
1379
- if (added) {
1380
- assertPolymorphicType(identifier, this.belongsToRelationship.definition, added, store);
1381
- }
1382
- }
1383
- const newData = {};
1384
-
1385
- // only set data if it was passed in
1386
- if (doc.data || doc.data === null) {
1387
- newData.data = added;
1388
- }
1389
- if ('links' in doc) {
1390
- newData.links = doc.links;
1391
- }
1392
- if ('meta' in doc) {
1393
- newData.meta = doc.meta;
1394
- }
1395
- store._join(() => {
1396
- this.graph.push({
1397
- op: 'updateRelationship',
1398
- record: identifier,
1399
- field: this.key,
1400
- value: newData
1401
- });
1402
- });
1403
- if (!skipFetch) return this.load();
1404
- }
1405
-
1406
- /**
1407
- `value()` synchronously returns the current value of the belongs-to
1408
- relationship. Unlike `record.relationshipName`, calling
1409
- `value()` on a reference does not trigger a fetch if the async
1410
- relationship is not yet loaded. If the relationship is not loaded
1411
- it will always return `null`.
1412
- Example
1413
- ```javascript
1414
- // models/blog.js
1415
- import Model, { belongsTo } from '@ember-data/model';
1416
- export default class BlogModel extends Model {
1417
- @belongsTo('user', { async: true, inverse: null }) user;
1418
- }
1419
- let blog = store.push({
1420
- data: {
1421
- type: 'blog',
1422
- id: 1,
1423
- relationships: {
1424
- user: {
1425
- data: { type: 'user', id: 1 }
1426
- }
1427
- }
1428
- }
1429
- });
1430
- let userRef = blog.belongsTo('user');
1431
- userRef.value(); // null
1432
- // provide data for reference
1433
- userRef.push({
1434
- data: {
1435
- type: 'user',
1436
- id: 1,
1437
- attributes: {
1438
- username: "@user"
1439
- }
1440
- }
1441
- }).then(function(user) {
1442
- userRef.value(); // user
1443
- });
1444
- ```
1445
- @public
1446
- @return {Model} the record in this relationship
1447
- */
1448
- value() {
1449
- const resource = this._resource();
1450
- return resource && resource.data ? this.store.peekRecord(resource.data) : null;
1451
- }
1452
-
1453
- /**
1454
- Loads a record in a belongs-to relationship if it is not already
1455
- loaded. If the relationship is already loaded this method does not
1456
- trigger a new load.
1457
- Example
1458
- ```javascript
1459
- // models/blog.js
1460
- import Model, { belongsTo } from '@ember-data/model';
1461
- export default class BlogModel extends Model {
1462
- @belongsTo('user', { async: true, inverse: null }) user;
1463
- }
1464
- let blog = store.push({
1465
- data: {
1466
- type: 'blog',
1467
- id: 1,
1468
- relationships: {
1469
- user: {
1470
- data: { type: 'user', id: 1 }
1471
- }
1472
- }
1473
- }
1474
- });
1475
- let userRef = blog.belongsTo('user');
1476
- userRef.value(); // null
1477
- userRef.load().then(function(user) {
1478
- userRef.value() === user
1479
- });
1480
- ```
1481
- You may also pass in an options object whose properties will be
1482
- fed forward. This enables you to pass `adapterOptions` into the
1483
- request given to the adapter via the reference.
1484
- Example
1485
- ```javascript
1486
- userRef.load({ adapterOptions: { isPrivate: true } }).then(function(user) {
1487
- userRef.value() === user;
1488
- });
1489
- ```
1490
- ```js [app/adapters/user.js]
1491
- import Adapter from '@ember-data/adapter';
1492
- export default class UserAdapter extends Adapter {
1493
- findRecord(store, type, id, snapshot) {
1494
- // In the adapter you will have access to adapterOptions.
1495
- let adapterOptions = snapshot.adapterOptions;
1496
- }
1497
- });
1498
- ```
1499
- @public
1500
- @param {Object} options the options to pass in.
1501
- @return {Promise} a promise that resolves with the record in this belongs-to relationship.
1502
- */
1503
- async load(options) {
1504
- const support = LEGACY_SUPPORT.get(this.___identifier);
1505
- const fetchSyncRel = !this.belongsToRelationship.definition.isAsync && !areAllInverseRecordsLoaded(this.store, this._resource());
1506
- return fetchSyncRel ? support.reloadBelongsTo(this.key, options).then(() => this.value()) :
1507
- // we cast to fix the return type since typescript and eslint don't understand async functions
1508
- // properly
1509
- support.getBelongsTo(this.key, options);
1510
- }
1511
-
1512
- /**
1513
- Triggers a reload of the value in this relationship. If the
1514
- remoteType is `"link"` Ember Data will use the relationship link to
1515
- reload the relationship. Otherwise it will reload the record by its
1516
- id.
1517
- Example
1518
- ```javascript
1519
- // models/blog.js
1520
- import Model, { belongsTo } from '@ember-data/model';
1521
- export default class BlogModel extends Model {
1522
- @belongsTo('user', { async: true, inverse: null }) user;
1523
- }
1524
- let blog = store.push({
1525
- data: {
1526
- type: 'blog',
1527
- id: 1,
1528
- relationships: {
1529
- user: {
1530
- data: { type: 'user', id: 1 }
1531
- }
1532
- }
1533
- }
1534
- });
1535
- let userRef = blog.belongsTo('user');
1536
- userRef.reload().then(function(user) {
1537
- userRef.value() === user
1538
- });
1539
- ```
1540
- You may also pass in an options object whose properties will be
1541
- fed forward. This enables you to pass `adapterOptions` into the
1542
- request given to the adapter via the reference. A full example
1543
- can be found in the `load` method.
1544
- Example
1545
- ```javascript
1546
- userRef.reload({ adapterOptions: { isPrivate: true } })
1547
- ```
1548
- @public
1549
- @param {Object} options the options to pass in.
1550
- @return {Promise} a promise that resolves with the record in this belongs-to relationship after the reload has completed.
1551
- */
1552
- reload(options) {
1553
- const support = LEGACY_SUPPORT.get(this.___identifier);
1554
- return support.reloadBelongsTo(this.key, options).then(() => this.value());
1555
- }
1556
- }
1557
- defineNonEnumerableSignal(BelongsToReference.prototype, '_ref', 0);
1558
- const LEGACY_SUPPORT = getOrSetGlobal('LEGACY_SUPPORT', new Map());
1559
- function lookupLegacySupport(record) {
1560
- const identifier = recordIdentifierFor(record);
1561
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1562
- if (!test) {
1563
- throw new Error(`Expected a record`);
1564
- }
1565
- })(identifier) : {};
1566
- let support = LEGACY_SUPPORT.get(identifier);
1567
- if (!support) {
1568
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1569
- if (!test) {
1570
- throw new Error(`Memory Leak Detected`);
1571
- }
1572
- })(!record.isDestroyed && !record.isDestroying) : {};
1573
- support = new LegacySupport(record);
1574
- LEGACY_SUPPORT.set(identifier, support);
1575
- LEGACY_SUPPORT.set(record, support);
1576
- }
1577
- return support;
1578
- }
1579
- class LegacySupport {
1580
- constructor(record) {
1581
- this.record = record;
1582
- this.store = storeFor(record);
1583
- this.identifier = recordIdentifierFor(record);
1584
- this.cache = peekCache(record);
1585
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1586
- const graphFor = importSync('@ember-data/graph/-private').graphFor;
1587
- this.graph = graphFor(this.store);
1588
- }
1589
- this._manyArrayCache = Object.create(null);
1590
- this._relationshipPromisesCache = Object.create(null);
1591
- this._relationshipProxyCache = Object.create(null);
1592
- this._pending = Object.create(null);
1593
- this.references = Object.create(null);
1594
- }
1595
- _syncArray(array) {
1596
- // It’s possible the parent side of the relationship may have been destroyed by this point
1597
- if (this.isDestroyed || this.isDestroying) {
1598
- return;
1599
- }
1600
- const currentState = array[SOURCE];
1601
- const identifier = this.identifier;
1602
- const [identifiers, jsonApi] = this._getCurrentState(identifier, array.key);
1603
- if (jsonApi.meta) {
1604
- array.meta = jsonApi.meta;
1605
- }
1606
- if (jsonApi.links) {
1607
- array.links = jsonApi.links;
1608
- }
1609
- currentState.length = 0;
1610
- fastPush(currentState, identifiers);
1611
- }
1612
- mutate(mutation) {
1613
- this.cache.mutate(mutation);
1614
- }
1615
- _findBelongsTo(key, resource, relationship, options) {
1616
- // TODO @runspired follow up if parent isNew then we should not be attempting load here
1617
- // TODO @runspired follow up on whether this should be in the relationship requests cache
1618
- return this._findBelongsToByJsonApiResource(resource, this.identifier, relationship, options).then(identifier => handleCompletedRelationshipRequest(this, key, relationship, identifier), e => handleCompletedRelationshipRequest(this, key, relationship, null, e));
1619
- }
1620
- reloadBelongsTo(key, options) {
1621
- const loadingPromise = this._relationshipPromisesCache[key];
1622
- if (loadingPromise) {
1623
- return loadingPromise;
1624
- }
1625
- const relationship = this.graph.get(this.identifier, key);
1626
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1627
- if (!test) {
1628
- throw new Error(`Expected ${key} to be a belongs-to relationship`);
1629
- }
1630
- })(isBelongsTo(relationship)) : {};
1631
- const resource = this.cache.getRelationship(this.identifier, key);
1632
- relationship.state.hasFailedLoadAttempt = false;
1633
- relationship.state.shouldForceReload = true;
1634
- const promise = this._findBelongsTo(key, resource, relationship, options);
1635
- if (this._relationshipProxyCache[key]) {
1636
- // @ts-expect-error
1637
- return this._updatePromiseProxyFor('belongsTo', key, {
1638
- promise
1639
- });
1640
- }
1641
- return promise;
1642
- }
1643
- getBelongsTo(key, options) {
1644
- const {
1645
- identifier,
1646
- cache
1647
- } = this;
1648
- const resource = cache.getRelationship(this.identifier, key);
1649
- const relatedIdentifier = resource && resource.data ? resource.data : null;
1650
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1651
- if (!test) {
1652
- throw new Error(`Expected a stable identifier`);
1653
- }
1654
- })(!relatedIdentifier || isStableIdentifier(relatedIdentifier)) : {};
1655
- const store = this.store;
1656
- const relationship = this.graph.get(this.identifier, key);
1657
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1658
- if (!test) {
1659
- throw new Error(`Expected ${key} to be a belongs-to relationship`);
1660
- }
1661
- })(isBelongsTo(relationship)) : {};
1662
- const isAsync = relationship.definition.isAsync;
1663
- const _belongsToState = {
1664
- key,
1665
- store,
1666
- legacySupport: this,
1667
- modelName: relationship.definition.type
1668
- };
1669
- if (isAsync) {
1670
- if (relationship.state.hasFailedLoadAttempt) {
1671
- return this._relationshipProxyCache[key];
1672
- }
1673
- const promise = this._findBelongsTo(key, resource, relationship, options);
1674
- const isLoaded = relatedIdentifier && store._instanceCache.recordIsLoaded(relatedIdentifier);
1675
- return this._updatePromiseProxyFor('belongsTo', key, {
1676
- promise,
1677
- content: isLoaded ? store._instanceCache.getRecord(relatedIdentifier) : null,
1678
- _belongsToState
1679
- });
1680
- } else {
1681
- if (relatedIdentifier === null) {
1682
- return null;
1683
- } else {
1684
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1685
- if (!test) {
1686
- throw new Error(`You looked up the '${key}' relationship on a '${identifier.type}' with id ${identifier.id || 'null'} but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (\`belongsTo(<type>, { async: true, inverse: <inverse> })\`)`);
1687
- }
1688
- })(store._instanceCache.recordIsLoaded(relatedIdentifier, true)) : {};
1689
- return store._instanceCache.getRecord(relatedIdentifier);
1690
- }
1691
- }
1692
- }
1693
- setDirtyBelongsTo(key, value) {
1694
- return this.cache.mutate({
1695
- op: 'replaceRelatedRecord',
1696
- record: this.identifier,
1697
- field: key,
1698
- value: extractIdentifierFromRecord(value)
1699
- },
1700
- // @ts-expect-error
1701
- true);
1702
- }
1703
- _getCurrentState(identifier, field) {
1704
- const jsonApi = this.cache.getRelationship(identifier, field);
1705
- const cache = this.store._instanceCache;
1706
- const identifiers = [];
1707
- if (jsonApi.data) {
1708
- for (let i = 0; i < jsonApi.data.length; i++) {
1709
- const relatedIdentifier = jsonApi.data[i];
1710
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1711
- if (!test) {
1712
- throw new Error(`Expected a stable identifier`);
1713
- }
1714
- })(isStableIdentifier(relatedIdentifier)) : {};
1715
- if (cache.recordIsLoaded(relatedIdentifier, true)) {
1716
- identifiers.push(relatedIdentifier);
1717
- }
1718
- }
1719
- }
1720
- return [identifiers, jsonApi];
1721
- }
1722
- getManyArray(key, definition) {
1723
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1724
- let manyArray = this._manyArrayCache[key];
1725
- if (!definition) {
1726
- definition = this.graph.get(this.identifier, key).definition;
1727
- }
1728
- if (!manyArray) {
1729
- const [identifiers, doc] = this._getCurrentState(this.identifier, key);
1730
- manyArray = new RelatedCollection({
1731
- store: this.store,
1732
- type: definition.type,
1733
- identifier: this.identifier,
1734
- cache: this.cache,
1735
- identifiers,
1736
- key,
1737
- meta: doc.meta || null,
1738
- links: doc.links || null,
1739
- isPolymorphic: definition.isPolymorphic,
1740
- isAsync: definition.isAsync,
1741
- _inverseIsAsync: definition.inverseIsAsync,
1742
- // @ts-expect-error Typescript doesn't have a way for us to thread the generic backwards so it infers unknown instead of T
1743
- manager: this,
1744
- isLoaded: !definition.isAsync,
1745
- allowMutation: true
1746
- });
1747
- this._manyArrayCache[key] = manyArray;
1748
- }
1749
- return manyArray;
1750
- }
1751
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1752
- {
1753
- throw new Error('hasMany only works with the @ember-data/json-api package');
1754
- }
1755
- })() : {};
1756
- }
1757
- fetchAsyncHasMany(key, relationship, manyArray, options) {
1758
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1759
- let loadingPromise = this._relationshipPromisesCache[key];
1760
- if (loadingPromise) {
1761
- return loadingPromise;
1762
- }
1763
- const jsonApi = this.cache.getRelationship(this.identifier, key);
1764
- const promise = this._findHasManyByJsonApiResource(jsonApi, this.identifier, relationship, options);
1765
- if (!promise) {
1766
- manyArray.isLoaded = true;
1767
- return Promise.resolve(manyArray);
1768
- }
1769
- loadingPromise = promise.then(() => handleCompletedRelationshipRequest(this, key, relationship, manyArray), e => handleCompletedRelationshipRequest(this, key, relationship, manyArray, e));
1770
- this._relationshipPromisesCache[key] = loadingPromise;
1771
- return loadingPromise;
1772
- }
1773
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1774
- {
1775
- throw new Error('hasMany only works with the @ember-data/json-api package');
1776
- }
1777
- })() : {};
1778
- }
1779
- reloadHasMany(key, options) {
1780
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1781
- const loadingPromise = this._relationshipPromisesCache[key];
1782
- if (loadingPromise) {
1783
- return loadingPromise;
1784
- }
1785
- const relationship = this.graph.get(this.identifier, key);
1786
- const {
1787
- definition,
1788
- state
1789
- } = relationship;
1790
- state.hasFailedLoadAttempt = false;
1791
- state.shouldForceReload = true;
1792
- const manyArray = this.getManyArray(key, definition);
1793
- const promise = this.fetchAsyncHasMany(key, relationship, manyArray, options);
1794
- if (this._relationshipProxyCache[key]) {
1795
- return this._updatePromiseProxyFor('hasMany', key, {
1796
- promise
1797
- });
1798
- }
1799
- return promise;
1800
- }
1801
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1802
- {
1803
- throw new Error(`hasMany only works with the @ember-data/json-api package`);
1804
- }
1805
- })() : {};
1806
- }
1807
- getHasMany(key, options) {
1808
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1809
- const relationship = this.graph.get(this.identifier, key);
1810
- const {
1811
- definition,
1812
- state
1813
- } = relationship;
1814
- const manyArray = this.getManyArray(key, definition);
1815
- if (definition.isAsync) {
1816
- if (state.hasFailedLoadAttempt) {
1817
- return this._relationshipProxyCache[key];
1818
- }
1819
- const promise = this.fetchAsyncHasMany(key, relationship, manyArray, options);
1820
- return this._updatePromiseProxyFor('hasMany', key, {
1821
- promise,
1822
- content: manyArray
1823
- });
1824
- } else {
1825
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1826
- if (!test) {
1827
- throw new Error(`You looked up the '${key}' relationship on a '${this.identifier.type}' with id ${this.identifier.id || 'null'} but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async ('hasMany(<type>, { async: true, inverse: <inverse> })')`);
1828
- }
1829
- })(!anyUnloaded(this.store, relationship)) : {};
1830
- return manyArray;
1831
- }
1832
- }
1833
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1834
- {
1835
- throw new Error(`hasMany only works with the @ember-data/json-api package`);
1836
- }
1837
- })() : {};
1838
- }
1839
- _updatePromiseProxyFor(kind, key, args) {
1840
- let promiseProxy = this._relationshipProxyCache[key];
1841
- if (kind === 'hasMany') {
1842
- const {
1843
- promise,
1844
- content
1845
- } = args;
1846
- if (promiseProxy) {
1847
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1848
- if (!test) {
1849
- throw new Error(`Expected a PromiseManyArray`);
1850
- }
1851
- })('_update' in promiseProxy) : {};
1852
- promiseProxy._update(promise, content);
1853
- } else {
1854
- promiseProxy = this._relationshipProxyCache[key] = new PromiseManyArray(promise, content);
1855
- }
1856
- return promiseProxy;
1857
- }
1858
- if (promiseProxy) {
1859
- const {
1860
- promise,
1861
- content
1862
- } = args;
1863
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1864
- if (!test) {
1865
- throw new Error(`Expected a PromiseBelongsTo`);
1866
- }
1867
- })('_belongsToState' in promiseProxy) : {};
1868
- if (content !== undefined) {
1869
- promiseProxy.set('content', content);
1870
- }
1871
- void promiseProxy.set('promise', promise);
1872
- } else {
1873
- promiseProxy = PromiseBelongsTo.create(args);
1874
- this._relationshipProxyCache[key] = promiseProxy;
1875
- }
1876
- return promiseProxy;
1877
- }
1878
- referenceFor(kind, name) {
1879
- let reference = this.references[name];
1880
- if (!reference) {
1881
- if (macroCondition(!dependencySatisfies('@ember-data/graph', '*'))) {
1882
- // TODO @runspired while this feels odd, it is not a regression in capability because we do
1883
- // not today support references pulling from RecordDatas other than our own
1884
- // because of the intimate API access involved. This is something we will need to redesign.
1885
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1886
- {
1887
- throw new Error(`snapshot.belongsTo only supported for @ember-data/json-api`);
1888
- }
1889
- })() : {};
1890
- }
1891
- const {
1892
- graph,
1893
- identifier
1894
- } = this;
1895
- const relationship = graph.get(identifier, name);
1896
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
1897
- if (kind) {
1898
- const modelName = identifier.type;
1899
- const actualRelationshipKind = relationship.definition.kind;
1900
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1901
- if (!test) {
1902
- throw new Error(`You tried to get the '${name}' relationship on a '${modelName}' via record.${kind}('${name}'), but the relationship is of kind '${actualRelationshipKind}'. Use record.${actualRelationshipKind}('${name}') instead.`);
1903
- }
1904
- })(actualRelationshipKind === kind) : {};
1905
- }
1906
- }
1907
- const relationshipKind = relationship.definition.kind;
1908
- if (relationshipKind === 'belongsTo') {
1909
- reference = new BelongsToReference(this.store, graph, identifier, relationship, name);
1910
- } else if (relationshipKind === 'hasMany') {
1911
- reference = new HasManyReference(this.store, graph, identifier, relationship, name);
1912
- }
1913
- this.references[name] = reference;
1914
- }
1915
- return reference;
1916
- }
1917
- _findHasManyByJsonApiResource(resource, parentIdentifier, relationship, options = {}) {
1918
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1919
- if (!resource) {
1920
- return;
1921
- }
1922
- const {
1923
- definition,
1924
- state
1925
- } = relationship;
1926
- upgradeStore(this.store);
1927
- const adapter = this.store.adapterFor?.(definition.type);
1928
- const {
1929
- isStale,
1930
- hasDematerializedInverse,
1931
- hasReceivedData,
1932
- isEmpty,
1933
- shouldForceReload
1934
- } = state;
1935
- const allInverseRecordsAreLoaded = areAllInverseRecordsLoaded(this.store, resource);
1936
- const identifiers = resource.data;
1937
- const shouldFindViaLink = resource.links && resource.links.related && (typeof adapter?.findHasMany === 'function' || typeof identifiers === 'undefined') && (shouldForceReload || hasDematerializedInverse || isStale || !allInverseRecordsAreLoaded && !isEmpty);
1938
- const field = this.store.schema.fields({
1939
- type: definition.inverseType
1940
- }).get(definition.key);
1941
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1942
- if (!test) {
1943
- throw new Error(`Expected a hasMany field definition for ${definition.inverseType}.${definition.key}`);
1944
- }
1945
- })(field && field.kind === 'hasMany') : {};
1946
- const request = {
1947
- useLink: shouldFindViaLink,
1948
- field,
1949
- links: resource.links,
1950
- meta: resource.meta,
1951
- options,
1952
- record: parentIdentifier
1953
- };
1954
-
1955
- // fetch via link
1956
- if (shouldFindViaLink) {
1957
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1958
- if (!test) {
1959
- throw new Error(`Expected collection to be an array`);
1960
- }
1961
- })(!identifiers || Array.isArray(identifiers)) : {};
1962
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1963
- if (!test) {
1964
- throw new Error(`Expected stable identifiers`);
1965
- }
1966
- })(!identifiers || identifiers.every(isStableIdentifier)) : {};
1967
- const req = field.options.linksMode ? {
1968
- url: getRelatedLink(resource),
1969
- op: 'findHasMany',
1970
- method: 'GET',
1971
- records: identifiers || [],
1972
- data: request,
1973
- [EnableHydration]: false
1974
- } : {
1975
- op: 'findHasMany',
1976
- records: identifiers || [],
1977
- data: request,
1978
- cacheOptions: {
1979
- [Symbol.for('wd:skip-cache')]: true
1980
- }
1981
- };
1982
- return this.store.request(req);
1983
- }
1984
- const preferLocalCache = hasReceivedData && !isEmpty;
1985
- const hasLocalPartialData = hasDematerializedInverse || isEmpty && Array.isArray(identifiers) && identifiers.length > 0;
1986
- const attemptLocalCache = !shouldForceReload && !isStale && (preferLocalCache || hasLocalPartialData);
1987
- if (attemptLocalCache && allInverseRecordsAreLoaded) {
1988
- return;
1989
- }
1990
- const hasData = hasReceivedData && !isEmpty;
1991
- if (attemptLocalCache || hasData || hasLocalPartialData) {
1992
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1993
- if (!test) {
1994
- throw new Error(`Expected collection to be an array`);
1995
- }
1996
- })(Array.isArray(identifiers)) : {};
1997
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1998
- if (!test) {
1999
- throw new Error(`Expected stable identifiers`);
2000
- }
2001
- })(identifiers.every(isStableIdentifier)) : {};
2002
- options.reload = options.reload || !attemptLocalCache || undefined;
2003
- return this.store.request({
2004
- op: 'findHasMany',
2005
- records: identifiers,
2006
- data: request,
2007
- cacheOptions: {
2008
- [Symbol.for('wd:skip-cache')]: true
2009
- }
2010
- });
2011
- }
2012
-
2013
- // we were explicitly told we have no data and no links.
2014
- // TODO if the relationshipIsStale, should we hit the adapter anyway?
2015
- return;
2016
- }
2017
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2018
- {
2019
- throw new Error(`hasMany only works with the @ember-data/json-api package`);
2020
- }
2021
- })() : {};
2022
- }
2023
- _findBelongsToByJsonApiResource(resource, parentIdentifier, relationship, options = {}) {
2024
- if (!resource) {
2025
- return Promise.resolve(null);
2026
- }
2027
- const key = relationship.definition.key;
2028
-
2029
- // interleaved promises mean that we MUST cache this here
2030
- // in order to prevent infinite re-render if the request
2031
- // fails.
2032
- if (this._pending[key]) {
2033
- return this._pending[key];
2034
- }
2035
- const identifier = resource.data ? resource.data : null;
2036
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2037
- if (!test) {
2038
- throw new Error(`Expected a stable identifier`);
2039
- }
2040
- })(!identifier || isStableIdentifier(identifier)) : {};
2041
- const {
2042
- isStale,
2043
- hasDematerializedInverse,
2044
- hasReceivedData,
2045
- isEmpty,
2046
- shouldForceReload
2047
- } = relationship.state;
2048
- const allInverseRecordsAreLoaded = areAllInverseRecordsLoaded(this.store, resource);
2049
- const shouldFindViaLink = resource.links?.related && (shouldForceReload || hasDematerializedInverse || isStale || !allInverseRecordsAreLoaded && !isEmpty);
2050
- const field = this.store.schema.fields(this.identifier).get(relationship.definition.key);
2051
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2052
- if (!test) {
2053
- throw new Error(`Attempted to access a belongsTo relationship but no definition exists for it`);
2054
- }
2055
- })(field && field.kind === 'belongsTo') : {};
2056
- const request = {
2057
- useLink: shouldFindViaLink,
2058
- field,
2059
- links: resource.links,
2060
- meta: resource.meta,
2061
- options,
2062
- record: parentIdentifier
2063
- };
2064
-
2065
- // fetch via link
2066
- if (shouldFindViaLink) {
2067
- const req = field.options.linksMode ? {
2068
- url: getRelatedLink(resource),
2069
- op: 'findBelongsTo',
2070
- method: 'GET',
2071
- records: identifier ? [identifier] : [],
2072
- data: request,
2073
- [EnableHydration]: false
2074
- } : {
2075
- op: 'findBelongsTo',
2076
- records: identifier ? [identifier] : [],
2077
- data: request,
2078
- cacheOptions: {
2079
- [Symbol.for('wd:skip-cache')]: true
2080
- }
2081
- };
2082
- const future = this.store.request(req);
2083
- this._pending[key] = future.then(doc => field.options.linksMode ? doc.content.data : doc.content).finally(() => {
2084
- this._pending[key] = undefined;
2085
- });
2086
- return this._pending[key];
2087
- }
2088
- const preferLocalCache = hasReceivedData && allInverseRecordsAreLoaded && !isEmpty;
2089
- const hasLocalPartialData = hasDematerializedInverse || isEmpty && resource.data;
2090
- // null is explicit empty, undefined is "we don't know anything"
2091
- const localDataIsEmpty = !identifier;
2092
- const attemptLocalCache = !shouldForceReload && !isStale && (preferLocalCache || hasLocalPartialData);
2093
-
2094
- // we dont need to fetch and are empty
2095
- if (attemptLocalCache && localDataIsEmpty) {
2096
- return Promise.resolve(null);
2097
- }
2098
-
2099
- // we dont need to fetch because we are local state
2100
- const resourceIsLocal = identifier?.id === null;
2101
- if (attemptLocalCache && allInverseRecordsAreLoaded || resourceIsLocal) {
2102
- return Promise.resolve(identifier);
2103
- }
2104
-
2105
- // we may need to fetch
2106
- if (identifier) {
2107
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2108
- if (!test) {
2109
- throw new Error(`Cannot fetch belongs-to relationship with no information`);
2110
- }
2111
- })(identifier) : {};
2112
- options.reload = options.reload || !attemptLocalCache || undefined;
2113
- this._pending[key] = this.store.request({
2114
- op: 'findBelongsTo',
2115
- records: [identifier],
2116
- data: request,
2117
- cacheOptions: {
2118
- [Symbol.for('wd:skip-cache')]: true
2119
- }
2120
- }).then(doc => doc.content).finally(() => {
2121
- this._pending[key] = undefined;
2122
- });
2123
- return this._pending[key];
2124
- }
2125
-
2126
- // we were explicitly told we have no data and no links.
2127
- // TODO if the relationshipIsStale, should we hit the adapter anyway?
2128
- return Promise.resolve(null);
2129
- }
2130
- destroy() {
2131
- this.isDestroying = true;
2132
- let cache = this._manyArrayCache;
2133
- this._manyArrayCache = Object.create(null);
2134
- Object.keys(cache).forEach(key => {
2135
- cache[key].destroy();
2136
- });
2137
- cache = this._relationshipProxyCache;
2138
- this._relationshipProxyCache = Object.create(null);
2139
- Object.keys(cache).forEach(key => {
2140
- const proxy = cache[key];
2141
- if (proxy.destroy) {
2142
- proxy.destroy();
2143
- }
2144
- });
2145
- cache = this.references;
2146
- this.references = Object.create(null);
2147
- Object.keys(cache).forEach(key => {
2148
- cache[key].destroy();
2149
- });
2150
- this.isDestroyed = true;
2151
- }
2152
- }
2153
- function getRelatedLink(resource) {
2154
- const related = resource.links?.related;
2155
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2156
- if (!test) {
2157
- throw new Error(`Expected a related link`);
2158
- }
2159
- })(related) : {};
2160
- return typeof related === 'object' ? related.href : related;
2161
- }
2162
- function handleCompletedRelationshipRequest(recordExt, key, relationship, value, error) {
2163
- delete recordExt._relationshipPromisesCache[key];
2164
- relationship.state.shouldForceReload = false;
2165
- const isHasMany = relationship.definition.kind === 'hasMany';
2166
- if (isHasMany) {
2167
- // we don't notify the record property here to avoid refetch
2168
- // only the many array
2169
- notifyInternalSignal(value[ARRAY_SIGNAL]);
2170
- }
2171
- if (error) {
2172
- relationship.state.hasFailedLoadAttempt = true;
2173
- const proxy = recordExt._relationshipProxyCache[key];
2174
- // belongsTo relationships are sometimes unloaded
2175
- // when a load fails, in this case we need
2176
- // to make sure that we aren't proxying
2177
- // to destroyed content
2178
- // for the sync belongsTo reload case there will be no proxy
2179
- // for the async reload case there will be no proxy if the ui
2180
- // has never been accessed
2181
- if (proxy && !isHasMany) {
2182
- // @ts-expect-error unsure why this is not resolving the boolean but async belongsTo is weird
2183
- if (proxy.content && proxy.content.isDestroying) {
2184
- proxy.set('content', null);
2185
- }
2186
- recordExt.store.notifications._flush();
2187
- }
2188
- throw error;
2189
- }
2190
- if (isHasMany) {
2191
- value.isLoaded = true;
2192
- } else {
2193
- recordExt.store.notifications._flush();
2194
- }
2195
- relationship.state.hasFailedLoadAttempt = false;
2196
- // only set to not stale if no error is thrown
2197
- relationship.state.isStale = false;
2198
- return isHasMany || !value ? value : recordExt.store.peekRecord(value);
2199
- }
2200
- function extractIdentifierFromRecord(record) {
2201
- if (!record) {
2202
- return null;
2203
- }
2204
- return recordIdentifierFor(record);
2205
- }
2206
- function anyUnloaded(store, relationship) {
2207
- const graph = store._graph;
2208
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2209
- if (!test) {
2210
- throw new Error(`Expected a Graph instance to be available`);
2211
- }
2212
- })(graph) : {};
2213
- const relationshipData = graph.getData(relationship.identifier, relationship.definition.key);
2214
- const state = relationshipData.data;
2215
- const cache = store._instanceCache;
2216
- const unloaded = state?.find(s => {
2217
- const isLoaded = cache.recordIsLoaded(s, true);
2218
- return !isLoaded;
2219
- });
2220
- return unloaded || false;
2221
- }
2222
- function areAllInverseRecordsLoaded(store, resource) {
2223
- const instanceCache = store._instanceCache;
2224
- const identifiers = resource.data;
2225
- if (Array.isArray(identifiers)) {
2226
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2227
- if (!test) {
2228
- throw new Error(`Expected stable identifiers`);
2229
- }
2230
- })(identifiers.every(isStableIdentifier)) : {};
2231
- // treat as collection
2232
- // check for unloaded records
2233
- return identifiers.every(identifier => instanceCache.recordIsLoaded(identifier));
2234
- }
2235
-
2236
- // treat as single resource
2237
- if (!identifiers) return true;
2238
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2239
- if (!test) {
2240
- throw new Error(`Expected stable identifiers`);
2241
- }
2242
- })(isStableIdentifier(identifiers)) : {};
2243
- return instanceCache.recordIsLoaded(identifiers);
2244
- }
2245
- function isBelongsTo(relationship) {
2246
- return relationship.definition.kind === 'belongsTo';
2247
- }
2248
-
2249
- // we force the type here to our own construct because mixin and extend patterns
2250
- // lose generic signatures. We also do this because we need to Omit `clear` from
2251
- // the type of ArrayProxy as we override it's signature.
2252
- const ArrayProxyWithCustomOverrides = ArrayProxy;
2253
-
2254
- /**
2255
- Holds validation errors for a given record, organized by attribute names.
2256
-
2257
- This class is not directly instantiable.
2258
-
2259
- Every `Model` has an `errors` property that is an instance of
2260
- `Errors`. This can be used to display validation error
2261
- messages returned from the server when a `record.save()` rejects.
2262
-
2263
- For Example, if you had a `User` model that looked like this:
2264
-
2265
- ```js [app/models/user.js]
2266
- import Model, { attr } from '@ember-data/model';
2267
-
2268
- export default class UserModel extends Model {
2269
- @attr('string') username;
2270
- @attr('string') email;
2271
- }
2272
- ```
2273
- And you attempted to save a record that did not validate on the backend:
2274
-
2275
- ```javascript
2276
- let user = store.createRecord('user', {
2277
- username: 'tomster',
2278
- email: 'invalidEmail'
2279
- });
2280
- user.save();
2281
- ```
2282
-
2283
- Your backend would be expected to return an error response that described
2284
- the problem, so that error messages can be generated on the app.
2285
-
2286
- API responses will be translated into instances of `Errors` differently,
2287
- depending on the specific combination of adapter and serializer used. You
2288
- may want to check the documentation or the source code of the libraries
2289
- that you are using, to know how they expect errors to be communicated.
2290
-
2291
- Errors can be displayed to the user by accessing their property name
2292
- to get an array of all the error objects for that property. Each
2293
- error object is a JavaScript object with two keys:
2294
-
2295
- - `message` A string containing the error message from the backend
2296
- - `attribute` The name of the property associated with this error message
2297
-
2298
- ```handlebars
2299
- <label>Username: <Input @value={{@model.username}} /> </label>
2300
- {{#each @model.errors.username as |error|}}
2301
- <div class="error">
2302
- {{error.message}}
2303
- </div>
2304
- {{/each}}
2305
-
2306
- <label>Email: <Input @value={{@model.email}} /> </label>
2307
- {{#each @model.errors.email as |error|}}
2308
- <div class="error">
2309
- {{error.message}}
2310
- </div>
2311
- {{/each}}
2312
- ```
2313
-
2314
- You can also access the special `messages` property on the error
2315
- object to get an array of all the error strings.
2316
-
2317
- ```handlebars
2318
- {{#each @model.errors.messages as |message|}}
2319
- <div class="error">
2320
- {{message}}
2321
- </div>
2322
- {{/each}}
2323
- ```
2324
-
2325
- @class Errors
2326
- @public
2327
- */
2328
- class Errors extends ArrayProxyWithCustomOverrides {
2329
- /**
2330
- @property errorsByAttributeName
2331
- @type {MapWithDefault}
2332
- @private
2333
- */
2334
- get errorsByAttributeName() {
2335
- return new Map();
2336
- }
2337
-
2338
- /**
2339
- Returns errors for a given attribute
2340
- ```javascript
2341
- let user = store.createRecord('user', {
2342
- username: 'tomster',
2343
- email: 'invalidEmail'
2344
- });
2345
- user.save().catch(function(){
2346
- user.errors.errorsFor('email'); // returns:
2347
- // [{attribute: "email", message: "Doesn't look like a valid email."}]
2348
- });
2349
- ```
2350
- @public
2351
- @param {String} attribute
2352
- @return {Array}
2353
- */
2354
- static {
2355
- decorateMethodV2(this.prototype, "errorsByAttributeName", [computed()]);
2356
- }
2357
- errorsFor(attribute) {
2358
- const map = this.errorsByAttributeName;
2359
- let errors = map.get(attribute);
2360
- if (errors === undefined) {
2361
- errors = A();
2362
- map.set(attribute, errors);
2363
- }
2364
-
2365
- // Errors may be a native array with extensions turned on. Since we access
2366
- // the array via a method, and not a computed or using `Ember.get`, it does
2367
- // not entangle properly with autotracking, so we entangle manually by
2368
- // getting the `[]` property.
2369
- get(errors, '[]');
2370
- return errors;
2371
- }
2372
-
2373
- /**
2374
- An array containing all of the error messages for this
2375
- record. This is useful for displaying all errors to the user.
2376
- ```handlebars
2377
- {{#each @model.errors.messages as |message|}}
2378
- <div class="error">
2379
- {{message}}
2380
- </div>
2381
- {{/each}}
2382
- ```
2383
- @property messages
2384
- @public
2385
- @type {Array}
2386
- */
2387
- static {
2388
- decorateFieldV2(this.prototype, "messages", [mapBy('content', 'message')]);
2389
- }
2390
- #messages = (initializeDeferredDecorator(this, "messages"), void 0);
2391
- /**
2392
- @property content
2393
- @type {Array}
2394
- @private
2395
- */
2396
- get content() {
2397
- return A();
2398
- }
2399
-
2400
- /**
2401
- @private
2402
- */
2403
- static {
2404
- decorateMethodV2(this.prototype, "content", [computed()]);
2405
- }
2406
- unknownProperty(attribute) {
2407
- const errors = this.errorsFor(attribute);
2408
- if (errors.length === 0) {
2409
- return undefined;
2410
- }
2411
- return errors;
2412
- }
2413
-
2414
- /**
2415
- Total number of errors.
2416
- @property length
2417
- @type {Number}
2418
- @public
2419
- @readonly
2420
- */
2421
-
2422
- /**
2423
- `true` if we have no errors.
2424
- @property isEmpty
2425
- @type {Boolean}
2426
- @public
2427
- @readonly
2428
- */
2429
- static {
2430
- decorateFieldV2(this.prototype, "isEmpty", [not('length')]);
2431
- }
2432
- #isEmpty = (initializeDeferredDecorator(this, "isEmpty"), void 0);
2433
- /**
2434
- Manually adds errors to the record. This will trigger the `becameInvalid` event/ lifecycle method on
2435
- the record and transition the record into an `invalid` state.
2436
- Example
2437
- ```javascript
2438
- let errors = user.errors;
2439
- // add multiple errors
2440
- errors.add('password', [
2441
- 'Must be at least 12 characters',
2442
- 'Must contain at least one symbol',
2443
- 'Cannot contain your name'
2444
- ]);
2445
- errors.errorsFor('password');
2446
- // =>
2447
- // [
2448
- // { attribute: 'password', message: 'Must be at least 12 characters' },
2449
- // { attribute: 'password', message: 'Must contain at least one symbol' },
2450
- // { attribute: 'password', message: 'Cannot contain your name' },
2451
- // ]
2452
- // add a single error
2453
- errors.add('username', 'This field is required');
2454
- errors.errorsFor('username');
2455
- // =>
2456
- // [
2457
- // { attribute: 'username', message: 'This field is required' },
2458
- // ]
2459
- ```
2460
- @public
2461
- @param {String} attribute - the property name of an attribute or relationship
2462
- @param {string[]|string} messages - an error message or array of error messages for the attribute
2463
- */
2464
- add(attribute, messages) {
2465
- const errors = this._findOrCreateMessages(attribute, messages);
2466
- this.addObjects(errors);
2467
- this.errorsFor(attribute).addObjects(errors);
2468
- this.__record.currentState.notify('isValid');
2469
- this.notifyPropertyChange(attribute);
2470
- }
2471
-
2472
- /**
2473
- @private
2474
- */
2475
- _findOrCreateMessages(attribute, messages) {
2476
- const errors = this.errorsFor(attribute);
2477
- const messagesArray = Array.isArray(messages) ? messages : [messages];
2478
- const _messages = new Array(messagesArray.length);
2479
- for (let i = 0; i < messagesArray.length; i++) {
2480
- const message = messagesArray[i];
2481
- const err = errors.findBy('message', message);
2482
- if (err) {
2483
- _messages[i] = err;
2484
- } else {
2485
- _messages[i] = {
2486
- attribute: attribute,
2487
- message
2488
- };
2489
- }
2490
- }
2491
- return _messages;
2492
- }
2493
-
2494
- /**
2495
- Manually removes all errors for a given member from the record.
2496
- This will transition the record into a `valid` state, and
2497
- triggers the `becameValid` event and lifecycle method.
2498
- Example:
2499
- ```javascript
2500
- let errors = user.errors;
2501
- errors.add('phone', ['error-1', 'error-2']);
2502
- errors.errorsFor('phone');
2503
- // =>
2504
- // [
2505
- // { attribute: 'phone', message: 'error-1' },
2506
- // { attribute: 'phone', message: 'error-2' },
2507
- // ]
2508
- errors.remove('phone');
2509
- errors.errorsFor('phone');
2510
- // => undefined
2511
- ```
2512
- @public
2513
- @param {String} member - the property name of an attribute or relationship
2514
- */
2515
- remove(attribute) {
2516
- if (this.isEmpty) {
2517
- return;
2518
- }
2519
- const content = this.rejectBy('attribute', attribute);
2520
- this.content.setObjects(content);
2521
-
2522
- // Although errorsByAttributeName.delete is technically enough to sync errors state, we also
2523
- // must mutate the array as well for autotracking
2524
- const errors = this.errorsFor(attribute);
2525
- for (let i = 0; i < errors.length; i++) {
2526
- if (errors[i].attribute === attribute) {
2527
- // .replace from Ember.NativeArray is necessary. JS splice will not work.
2528
- errors.replace(i, 1);
2529
- }
2530
- }
2531
- this.errorsByAttributeName.delete(attribute);
2532
- this.__record.currentState.notify('isValid');
2533
- this.notifyPropertyChange(attribute);
2534
- this.notifyPropertyChange('length');
2535
- }
2536
-
2537
- /**
2538
- Manually clears all errors for the record.
2539
- This will transition the record into a `valid` state, and
2540
- will trigger the `becameValid` event and lifecycle method.
2541
- Example:
2542
- ```javascript
2543
- let errors = user.errors;
2544
- errors.add('username', ['error-a']);
2545
- errors.add('phone', ['error-1', 'error-2']);
2546
- errors.errorsFor('username');
2547
- // =>
2548
- // [
2549
- // { attribute: 'username', message: 'error-a' },
2550
- // ]
2551
- errors.errorsFor('phone');
2552
- // =>
2553
- // [
2554
- // { attribute: 'phone', message: 'error-1' },
2555
- // { attribute: 'phone', message: 'error-2' },
2556
- // ]
2557
- errors.clear();
2558
- errors.errorsFor('username');
2559
- // => undefined
2560
- errors.errorsFor('phone');
2561
- // => undefined
2562
- errors.messages
2563
- // => []
2564
- ```
2565
- @public
2566
- */
2567
- clear() {
2568
- if (this.isEmpty) {
2569
- return;
2570
- }
2571
- const errorsByAttributeName = this.errorsByAttributeName;
2572
- const attributes = [];
2573
- errorsByAttributeName.forEach(function (_, attribute) {
2574
- attributes.push(attribute);
2575
- });
2576
- errorsByAttributeName.clear();
2577
- attributes.forEach(attribute => {
2578
- this.notifyPropertyChange(attribute);
2579
- });
2580
- this.__record.currentState.notify('isValid');
2581
- super.clear();
2582
- }
2583
-
2584
- /**
2585
- Checks if there are error messages for the given attribute.
2586
- ```js [app/controllers/user/edit.js]
2587
- export default class UserEditController extends Controller {
2588
- @action
2589
- save(user) {
2590
- if (user.errors.has('email')) {
2591
- return alert('Please update your email before attempting to save.');
2592
- }
2593
- user.save();
2594
- }
2595
- }
2596
- ```
2597
- @public
2598
- @param {String} attribute
2599
- @return {Boolean} true if there some errors on given attribute
2600
- */
2601
- has(attribute) {
2602
- return this.errorsFor(attribute).length > 0;
2603
- }
2604
- }
2605
- export { Errors as E, LEGACY_SUPPORT as L, PromiseBelongsTo as P, PromiseManyArray as a, decorateMethodV2 as d, lookupLegacySupport as l };