@ember-data/model 5.6.0-beta.0 → 5.6.0-beta.2

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 (76) hide show
  1. package/addon-main.cjs +1 -1
  2. package/dist/-private.js +1 -3
  3. package/dist/hooks.js +1 -2
  4. package/dist/index.js +1 -5
  5. package/dist/migration-support.js +1 -388
  6. package/package.json +7 -35
  7. package/unstable-preview-types/-private.d.ts +3 -12
  8. package/unstable-preview-types/hooks.d.ts +3 -4
  9. package/unstable-preview-types/index.d.ts +32 -64
  10. package/unstable-preview-types/migration-support.d.ts +21 -269
  11. package/dist/-private.js.map +0 -1
  12. package/dist/has-many-BXU96bZ9.js +0 -682
  13. package/dist/has-many-BXU96bZ9.js.map +0 -1
  14. package/dist/hooks-o1U_cEA3.js +0 -75
  15. package/dist/hooks-o1U_cEA3.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/model-Dkk-TZlL.js +0 -4899
  20. package/dist/model-Dkk-TZlL.js.map +0 -1
  21. package/dist/schema-provider-DyG6fJXt.js +0 -259
  22. package/dist/schema-provider-DyG6fJXt.js.map +0 -1
  23. package/unstable-preview-types/-private/attr.d.ts +0 -175
  24. package/unstable-preview-types/-private/attr.d.ts.map +0 -1
  25. package/unstable-preview-types/-private/attr.type-test.d.ts +0 -4
  26. package/unstable-preview-types/-private/attr.type-test.d.ts.map +0 -1
  27. package/unstable-preview-types/-private/belongs-to.d.ts +0 -181
  28. package/unstable-preview-types/-private/belongs-to.d.ts.map +0 -1
  29. package/unstable-preview-types/-private/belongs-to.type-test.d.ts +0 -4
  30. package/unstable-preview-types/-private/belongs-to.type-test.d.ts.map +0 -1
  31. package/unstable-preview-types/-private/debug/assert-polymorphic-type.d.ts +0 -8
  32. package/unstable-preview-types/-private/debug/assert-polymorphic-type.d.ts.map +0 -1
  33. package/unstable-preview-types/-private/errors.d.ts +0 -303
  34. package/unstable-preview-types/-private/errors.d.ts.map +0 -1
  35. package/unstable-preview-types/-private/has-many.d.ts +0 -169
  36. package/unstable-preview-types/-private/has-many.d.ts.map +0 -1
  37. package/unstable-preview-types/-private/has-many.type-test.d.ts +0 -4
  38. package/unstable-preview-types/-private/has-many.type-test.d.ts.map +0 -1
  39. package/unstable-preview-types/-private/hooks.d.ts +0 -13
  40. package/unstable-preview-types/-private/hooks.d.ts.map +0 -1
  41. package/unstable-preview-types/-private/legacy-relationships-support.d.ts +0 -60
  42. package/unstable-preview-types/-private/legacy-relationships-support.d.ts.map +0 -1
  43. package/unstable-preview-types/-private/model-for-mixin.d.ts +0 -6
  44. package/unstable-preview-types/-private/model-for-mixin.d.ts.map +0 -1
  45. package/unstable-preview-types/-private/model-methods.d.ts +0 -37
  46. package/unstable-preview-types/-private/model-methods.d.ts.map +0 -1
  47. package/unstable-preview-types/-private/model.d.ts +0 -1303
  48. package/unstable-preview-types/-private/model.d.ts.map +0 -1
  49. package/unstable-preview-types/-private/model.type-test.d.ts +0 -4
  50. package/unstable-preview-types/-private/model.type-test.d.ts.map +0 -1
  51. package/unstable-preview-types/-private/notify-changes.d.ts +0 -8
  52. package/unstable-preview-types/-private/notify-changes.d.ts.map +0 -1
  53. package/unstable-preview-types/-private/promise-belongs-to.d.ts +0 -46
  54. package/unstable-preview-types/-private/promise-belongs-to.d.ts.map +0 -1
  55. package/unstable-preview-types/-private/promise-many-array.d.ts +0 -136
  56. package/unstable-preview-types/-private/promise-many-array.d.ts.map +0 -1
  57. package/unstable-preview-types/-private/promise-proxy-base.d.ts +0 -5
  58. package/unstable-preview-types/-private/promise-proxy-base.d.ts.map +0 -1
  59. package/unstable-preview-types/-private/record-state.d.ts +0 -80
  60. package/unstable-preview-types/-private/record-state.d.ts.map +0 -1
  61. package/unstable-preview-types/-private/references/belongs-to.d.ts +0 -506
  62. package/unstable-preview-types/-private/references/belongs-to.d.ts.map +0 -1
  63. package/unstable-preview-types/-private/references/has-many.d.ts +0 -518
  64. package/unstable-preview-types/-private/references/has-many.d.ts.map +0 -1
  65. package/unstable-preview-types/-private/schema-provider.d.ts +0 -65
  66. package/unstable-preview-types/-private/schema-provider.d.ts.map +0 -1
  67. package/unstable-preview-types/-private/type-utils.d.ts +0 -64
  68. package/unstable-preview-types/-private/type-utils.d.ts.map +0 -1
  69. package/unstable-preview-types/-private/util.d.ts +0 -8
  70. package/unstable-preview-types/-private/util.d.ts.map +0 -1
  71. package/unstable-preview-types/-private.d.ts.map +0 -1
  72. package/unstable-preview-types/hooks.d.ts.map +0 -1
  73. package/unstable-preview-types/index.d.ts.map +0 -1
  74. package/unstable-preview-types/migration-support.d.ts.map +0 -1
  75. package/unstable-preview-types/migration-support.type-test.d.ts +0 -4
  76. package/unstable-preview-types/migration-support.type-test.d.ts.map +0 -1
@@ -1,4899 +0,0 @@
1
- import { deprecate } from '@ember/debug';
2
- import { dasherize } from '@ember-data/request-utils/string';
3
- import { macroCondition, getGlobalConfig, dependencySatisfies, importSync } from '@embroider/macros';
4
- import EmberObject, { computed, get } from '@ember/object';
5
- import { recordIdentifierFor as recordIdentifierFor$1, storeFor as storeFor$1 } from '@ember-data/store';
6
- import { memoized, defineSignal, defineNonEnumerableSignal, isStableIdentifier, recordIdentifierFor, storeFor, peekCache, SOURCE, fastPush, RelatedCollection, notifyInternalSignal, ARRAY_SIGNAL, peekInternalSignal, withSignalStore, gate, coerceId, entangleSignal } from '@ember-data/store/-private';
7
- import { RecordStore } from '@warp-drive/core-types/symbols';
8
- import { A } from '@ember/array';
9
- import ArrayProxy from '@ember/array/proxy';
10
- import { mapBy, not } from '@ember/object/computed';
11
- import { upgradeStore } from '@ember-data/legacy-compat/-private';
12
- import { getOrSetGlobal } from '@warp-drive/core-types/-private';
13
- import { EnableHydration } from '@warp-drive/core-types/request';
14
- import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
15
- import ObjectProxy from '@ember/object/proxy';
16
- import { cacheFor } from '@ember/object/internals';
17
- function isElementDescriptor(args) {
18
- const [maybeTarget, maybeKey, maybeDesc] = args;
19
- return (
20
- // Ensure we have the right number of args
21
- args.length === 3 && (
22
- // Make sure the target is a class or object (prototype)
23
- typeof maybeTarget === 'function' || typeof maybeTarget === 'object' && maybeTarget !== null) &&
24
- // Make sure the key is a string
25
- typeof maybeKey === 'string' && (
26
- // Make sure the descriptor is the right shape
27
- typeof maybeDesc === 'object' && maybeDesc !== null && 'enumerable' in maybeDesc && 'configurable' in maybeDesc ||
28
- // TS compatibility
29
- maybeDesc === undefined)
30
- );
31
- }
32
- function normalizeModelName(type) {
33
- if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_NON_STRICT_TYPES)) {
34
- const result = dasherize(type);
35
- deprecate(`The resource type '${type}' is not normalized. Update your application code to use '${result}' instead of '${type}'.`, result === type, {
36
- id: 'ember-data:deprecate-non-strict-types',
37
- until: '6.0',
38
- for: 'ember-data',
39
- since: {
40
- available: '4.13',
41
- enabled: '5.3'
42
- }
43
- });
44
- return result;
45
- }
46
- return type;
47
- }
48
- const PromiseObject = ObjectProxy.extend(PromiseProxyMixin);
49
- const deferred = /* @__PURE__ */new WeakMap();
50
- function deferDecorator(proto, prop, desc) {
51
- let map = deferred.get(proto);
52
- if (!map) {
53
- map = /* @__PURE__ */new Map();
54
- deferred.set(proto, map);
55
- }
56
- map.set(prop, desc);
57
- }
58
- function findDeferredDecorator(target, prop) {
59
- var _a;
60
- let cursor = target.prototype;
61
- while (cursor) {
62
- let desc = (_a = deferred.get(cursor)) == null ? void 0 : _a.get(prop);
63
- if (desc) {
64
- return desc;
65
- }
66
- cursor = cursor.prototype;
67
- }
68
- }
69
- function decorateFieldV2(prototype, prop, decorators, initializer) {
70
- let desc = {
71
- configurable: true,
72
- enumerable: true,
73
- writable: true,
74
- initializer: null
75
- };
76
- if (initializer) {
77
- desc.initializer = initializer;
78
- }
79
- for (let decorator of decorators) {
80
- desc = decorator(prototype, prop, desc) || desc;
81
- }
82
- if (desc.initializer === void 0) {
83
- Object.defineProperty(prototype, prop, desc);
84
- } else {
85
- deferDecorator(prototype, prop, desc);
86
- }
87
- }
88
- function decorateMethodV2(prototype, prop, decorators) {
89
- const origDesc = Object.getOwnPropertyDescriptor(prototype, prop);
90
- let desc = {
91
- ...origDesc
92
- };
93
- for (let decorator of decorators) {
94
- desc = decorator(prototype, prop, desc) || desc;
95
- }
96
- if (desc.initializer !== void 0) {
97
- desc.value = desc.initializer ? desc.initializer.call(prototype) : void 0;
98
- desc.initializer = void 0;
99
- }
100
- Object.defineProperty(prototype, prop, desc);
101
- }
102
- function initializeDeferredDecorator(target, prop) {
103
- let desc = findDeferredDecorator(target.constructor, prop);
104
- if (desc) {
105
- Object.defineProperty(target, prop, {
106
- enumerable: desc.enumerable,
107
- configurable: desc.configurable,
108
- writable: desc.writable,
109
- value: desc.initializer ? desc.initializer.call(target) : void 0
110
- });
111
- }
112
- }
113
- const LegacyPromiseProxy = Symbol.for('LegacyPromiseProxy');
114
-
115
- // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-extraneous-class
116
-
117
- const Extended = PromiseObject;
118
-
119
- /**
120
- @module @ember-data/model
121
- */
122
-
123
- /**
124
- A PromiseBelongsTo is a PromiseObject that also proxies certain method calls
125
- to the underlying belongsTo model.
126
- Right now we proxy:
127
- * `reload()`
128
- @class PromiseBelongsTo
129
- @extends PromiseObject
130
- @private
131
- */
132
- class PromiseBelongsTo extends Extended {
133
- get id() {
134
- const {
135
- key,
136
- legacySupport
137
- } = this._belongsToState;
138
- const ref = legacySupport.referenceFor('belongsTo', key);
139
- return ref.id();
140
- }
141
-
142
- // we don't proxy meta because we would need to proxy it to the relationship state container
143
- // however, meta on relationships does not trigger change notifications.
144
- // if you need relationship meta, you should do `record.belongsTo(relationshipName).meta()`
145
- static {
146
- decorateMethodV2(this.prototype, "id", [memoized]);
147
- }
148
- get meta() {
149
- // eslint-disable-next-line no-constant-condition
150
- {
151
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
152
- {
153
- 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.');
154
- }
155
- })() : {};
156
- }
157
- return;
158
- }
159
- static {
160
- decorateMethodV2(this.prototype, "meta", [computed()]);
161
- }
162
- async reload(options) {
163
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
164
- if (!test) {
165
- throw new Error('You are trying to reload an async belongsTo before it has been created');
166
- }
167
- })(this.content !== undefined) : {};
168
- const {
169
- key,
170
- legacySupport
171
- } = this._belongsToState;
172
- await legacySupport.reloadBelongsTo(key, options);
173
- return this;
174
- }
175
- [LegacyPromiseProxy] = true;
176
- }
177
-
178
- /**
179
- @module @ember-data/model
180
- */
181
- /**
182
- This class is returned as the result of accessing an async hasMany relationship
183
- on an instance of a Model extending from `@ember-data/model`.
184
-
185
- A PromiseManyArray is an iterable proxy that allows templates to consume related
186
- ManyArrays and update once their contents are no longer pending.
187
-
188
- In your JS code you should resolve the promise first.
189
-
190
- ```js
191
- const comments = await post.comments;
192
- ```
193
-
194
- @class PromiseManyArray
195
- @public
196
- */
197
- class PromiseManyArray {
198
- constructor(promise, content) {
199
- this._update(promise, content);
200
- this.isDestroyed = false;
201
- }
202
-
203
- /**
204
- * Retrieve the length of the content
205
- * @property length
206
- * @public
207
- */
208
- get length() {
209
- // shouldn't be needed, but ends up being needed
210
- // for computed chains even in 4.x
211
- if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_COMPUTED_CHAINS)) {
212
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
213
- this['[]'];
214
- }
215
- return this.content ? this.content.length : 0;
216
- }
217
-
218
- // this will error if someone tries to call
219
- // A(identifierArray) since it is not configurable
220
- // which is preferrable to the `meta` override we used
221
- // before which required importing all of Ember
222
- static {
223
- decorateMethodV2(this.prototype, "length", [memoized]);
224
- }
225
- get '[]'() {
226
- // ember-source < 3.23 (e.g. 3.20 lts)
227
- // requires that the tag `'[]'` be notified
228
- // on the ArrayProxy in order for `{{#each}}`
229
- // to recompute. We entangle content.
230
- return this.content?.length && this.content;
231
- }
232
-
233
- /**
234
- * Iterate the proxied content. Called by the glimmer iterator in #each
235
- * We do not guarantee that forEach will always be available. This
236
- * may eventually be made to use Symbol.Iterator once glimmer supports it.
237
- *
238
- * @method forEach
239
- * @param cb
240
- * @return
241
- * @private
242
- */
243
- static {
244
- decorateMethodV2(this.prototype, '[]', [memoized]);
245
- }
246
- forEach(cb) {
247
- if (this.content && this.length) {
248
- this.content.forEach(cb);
249
- }
250
- }
251
-
252
- /**
253
- * Reload the relationship
254
- * @method reload
255
- * @public
256
- * @param options
257
- * @return
258
- */
259
- reload(options) {
260
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
261
- if (!test) {
262
- throw new Error('You are trying to reload an async manyArray before it has been created');
263
- }
264
- })(this.content) : {};
265
- void this.content.reload(options);
266
- return this;
267
- }
268
-
269
- //---- Properties/Methods from the PromiseProxyMixin that we will keep as our API
270
-
271
- /**
272
- * Whether the loading promise is still pending
273
- *
274
- * @property isPending
275
- * @type {Boolean}
276
- * @public
277
- */
278
-
279
- /**
280
- * Whether the loading promise rejected
281
- *
282
- * @property isRejected
283
- * @type {Boolean}
284
- * @public
285
- */
286
-
287
- /**
288
- * Whether the loading promise succeeded
289
- *
290
- * @property isFulfilled
291
- * @type {Boolean}
292
- * @public
293
- */
294
-
295
- /**
296
- * Whether the loading promise completed (resolved or rejected)
297
- *
298
- * @property isSettled
299
- * @type {Boolean}
300
- * @public
301
- */
302
-
303
- /**
304
- * chain this promise
305
- *
306
- * @method then
307
- * @public
308
- * @param success
309
- * @param fail
310
- * @return Promise
311
- */
312
- then(s, f) {
313
- return this.promise.then(s, f);
314
- }
315
-
316
- /**
317
- * catch errors thrown by this promise
318
- * @method catch
319
- * @public
320
- * @param callback
321
- * @return Promise
322
- */
323
- catch(cb) {
324
- return this.promise.catch(cb);
325
- }
326
-
327
- /**
328
- * run cleanup after this promise completes
329
- *
330
- * @method finally
331
- * @public
332
- * @param callback
333
- * @return Promise
334
- */
335
- finally(cb) {
336
- return this.promise.finally(cb);
337
- }
338
-
339
- //---- Methods on EmberObject that we should keep
340
-
341
- destroy() {
342
- this.isDestroyed = true;
343
- this.content = null;
344
- this.promise = null;
345
- }
346
-
347
- //---- Methods/Properties on ManyArray that we own and proxy to
348
-
349
- /**
350
- * Retrieve the links for this relationship
351
- * @property links
352
- * @public
353
- */
354
- get links() {
355
- return this.content ? this.content.links : undefined;
356
- }
357
-
358
- /**
359
- * Retrieve the meta for this relationship
360
- * @property meta
361
- * @public
362
- */
363
- static {
364
- decorateMethodV2(this.prototype, "links", [memoized]);
365
- }
366
- get meta() {
367
- return this.content ? this.content.meta : undefined;
368
- }
369
-
370
- //---- Our own stuff
371
- static {
372
- decorateMethodV2(this.prototype, "meta", [memoized]);
373
- }
374
- _update(promise, content) {
375
- if (content !== undefined) {
376
- this.content = content;
377
- }
378
- this.promise = tapPromise(this, promise);
379
- }
380
- static create({
381
- promise,
382
- content
383
- }) {
384
- return new this(promise, content);
385
- }
386
- [LegacyPromiseProxy] = true;
387
- }
388
- defineSignal(PromiseManyArray.prototype, 'content', null);
389
- defineSignal(PromiseManyArray.prototype, 'isPending', false);
390
- defineSignal(PromiseManyArray.prototype, 'isRejected', false);
391
- defineSignal(PromiseManyArray.prototype, 'isFulfilled', false);
392
- defineSignal(PromiseManyArray.prototype, 'isSettled', false);
393
- function tapPromise(proxy, promise) {
394
- proxy.isPending = true;
395
- proxy.isSettled = false;
396
- proxy.isFulfilled = false;
397
- proxy.isRejected = false;
398
- return Promise.resolve(promise).then(content => {
399
- proxy.isPending = false;
400
- proxy.isFulfilled = true;
401
- proxy.isSettled = true;
402
- proxy.content = content;
403
- return content;
404
- }, error => {
405
- proxy.isPending = false;
406
- proxy.isFulfilled = false;
407
- proxy.isRejected = true;
408
- proxy.isSettled = true;
409
- throw error;
410
- });
411
- }
412
-
413
- /*
414
- Assert that `addedRecord` has a valid type so it can be added to the
415
- relationship of the `record`.
416
-
417
- The assert basically checks if the `addedRecord` can be added to the
418
- relationship (specified via `relationshipMeta`) of the `record`.
419
-
420
- This utility should only be used internally, as both record parameters must
421
- be stable record identifiers and the `relationshipMeta` needs to be the meta
422
- information about the relationship, retrieved via
423
- `record.relationshipFor(key)`.
424
- */
425
- let assertPolymorphicType;
426
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
427
- // eslint-disable-next-line @typescript-eslint/no-shadow
428
- assertPolymorphicType = function assertPolymorphicType(parentIdentifier, parentDefinition, addedIdentifier, store) {
429
- if (parentDefinition.inverseIsImplicit) {
430
- return;
431
- }
432
- if (parentDefinition.isPolymorphic) {
433
- const meta = store.schema.fields(addedIdentifier)?.get(parentDefinition.inverseKey);
434
- if (meta) {
435
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
436
- if (!test) {
437
- throw new Error(`Expected the schema for the field ${parentDefinition.inverseKey} on ${addedIdentifier.type} to be for a legacy relationship`);
438
- }
439
- })(meta.kind === 'belongsTo' || meta.kind === 'hasMany') : {};
440
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
441
- if (!test) {
442
- 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.`);
443
- }
444
- })(meta?.options?.as === parentDefinition.type) : {};
445
- }
446
- }
447
- };
448
- }
449
- function isResourceIdentiferWithRelatedLinks$1(value) {
450
- return Boolean(value && value.links && value.links.related);
451
- }
452
- /**
453
- A `HasManyReference` is a low-level API that allows access
454
- and manipulation of a hasMany relationship.
455
-
456
- It is especially useful when you're dealing with `async` relationships
457
- from `@ember-data/model` as it allows synchronous access to
458
- the relationship data if loaded, as well as APIs for loading, reloading
459
- the data or accessing available information without triggering a load.
460
-
461
- It may also be useful when using `sync` relationships with `@ember-data/model`
462
- that need to be loaded/reloaded with more precise timing than marking the
463
- relationship as `async` and relying on autofetch would have allowed.
464
-
465
- However,keep in mind that marking a relationship as `async: false` will introduce
466
- bugs into your application if the data is not always guaranteed to be available
467
- by the time the relationship is accessed. Ergo, it is recommended when using this
468
- approach to utilize `links` for unloaded relationship state instead of identifiers.
469
-
470
- Reference APIs are entangled with the relationship's underlying state,
471
- thus any getters or cached properties that utilize these will properly
472
- invalidate if the relationship state changes.
473
-
474
- References are "stable", meaning that multiple calls to retrieve the reference
475
- for a given relationship will always return the same HasManyReference.
476
-
477
- @class HasManyReference
478
- @public
479
- */
480
- class HasManyReference {
481
- /**
482
- * The field name on the parent record for this has-many relationship.
483
- *
484
- * @property key
485
- * @type {String}
486
- * @public
487
- */
488
-
489
- /**
490
- * The type of resource this relationship will contain.
491
- *
492
- * @property type
493
- * @type {String}
494
- * @public
495
- */
496
-
497
- // unsubscribe tokens given to us by the notification manager
498
- ___token;
499
- ___identifier;
500
- ___relatedTokenMap;
501
- constructor(store, graph, parentIdentifier, hasManyRelationship, key) {
502
- this.graph = graph;
503
- this.key = key;
504
- this.hasManyRelationship = hasManyRelationship;
505
- this.type = hasManyRelationship.definition.type;
506
- this.store = store;
507
- this.___identifier = parentIdentifier;
508
- this.___token = store.notifications.subscribe(parentIdentifier, (_, bucket, notifiedKey) => {
509
- if (bucket === 'relationships' && notifiedKey === key) {
510
- this._ref++;
511
- }
512
- });
513
- this.___relatedTokenMap = new Map();
514
- // TODO inverse
515
- }
516
-
517
- /**
518
- * This method should never be called by user code.
519
- *
520
- * @internal
521
- */
522
- destroy() {
523
- this.store.notifications.unsubscribe(this.___token);
524
- this.___relatedTokenMap.forEach(token => {
525
- this.store.notifications.unsubscribe(token);
526
- });
527
- this.___relatedTokenMap.clear();
528
- }
529
-
530
- /**
531
- * An array of identifiers for the records that this reference refers to.
532
- *
533
- * @property identifiers
534
- * @type {StableRecordIdentifier[]}
535
- * @public
536
- */
537
- get identifiers() {
538
- ensureRefCanSubscribe(this);
539
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
540
- this._ref;
541
- const resource = this._resource();
542
- const map = this.___relatedTokenMap;
543
- this.___relatedTokenMap = new Map();
544
- if (resource && resource.data) {
545
- return resource.data.map(resourceIdentifier => {
546
- const identifier = this.store.identifierCache.getOrCreateRecordIdentifier(resourceIdentifier);
547
- let token = map.get(identifier);
548
- if (token) {
549
- map.delete(identifier);
550
- } else {
551
- token = this.store.notifications.subscribe(identifier, (_, bucket, notifiedKey) => {
552
- if (bucket === 'identity' || bucket === 'attributes' && notifiedKey === 'id') {
553
- this._ref++;
554
- }
555
- });
556
- }
557
- this.___relatedTokenMap.set(identifier, token);
558
- return identifier;
559
- });
560
- }
561
- map.forEach(token => {
562
- this.store.notifications.unsubscribe(token);
563
- });
564
- map.clear();
565
- return [];
566
- }
567
- static {
568
- decorateMethodV2(this.prototype, "identifiers", [memoized]);
569
- }
570
- _resource() {
571
- const cache = this.store.cache;
572
- return cache.getRelationship(this.___identifier, this.key);
573
- }
574
-
575
- /**
576
- This returns a string that represents how the reference will be
577
- looked up when it is loaded. If the relationship has a link it will
578
- use the "link" otherwise it defaults to "id".
579
- Example
580
- ```app/models/post.js
581
- import Model, { hasMany } from '@ember-data/model';
582
- export default class PostModel extends Model {
583
- @hasMany('comment', { async: true, inverse: null }) comments;
584
- }
585
- ```
586
- ```javascript
587
- let post = store.push({
588
- data: {
589
- type: 'post',
590
- id: 1,
591
- relationships: {
592
- comments: {
593
- data: [{ type: 'comment', id: 1 }]
594
- }
595
- }
596
- }
597
- });
598
- let commentsRef = post.hasMany('comments');
599
- // get the identifier of the reference
600
- if (commentsRef.remoteType() === "ids") {
601
- let ids = commentsRef.ids();
602
- } else if (commentsRef.remoteType() === "link") {
603
- let link = commentsRef.link();
604
- }
605
- ```
606
- @method remoteType
607
- @public
608
- @return {String} The name of the remote type. This should either be `link` or `ids`
609
- */
610
- remoteType() {
611
- const value = this._resource();
612
- if (value && value.links && value.links.related) {
613
- return 'link';
614
- }
615
- return 'ids';
616
- }
617
-
618
- /**
619
- `ids()` returns an array of the record IDs in this relationship.
620
- Example
621
- ```app/models/post.js
622
- import Model, { hasMany } from '@ember-data/model';
623
- export default class PostModel extends Model {
624
- @hasMany('comment', { async: true, inverse: null }) comments;
625
- }
626
- ```
627
- ```javascript
628
- let post = store.push({
629
- data: {
630
- type: 'post',
631
- id: 1,
632
- relationships: {
633
- comments: {
634
- data: [{ type: 'comment', id: 1 }]
635
- }
636
- }
637
- }
638
- });
639
- let commentsRef = post.hasMany('comments');
640
- commentsRef.ids(); // ['1']
641
- ```
642
- @method ids
643
- @public
644
- @return {Array} The ids in this has-many relationship
645
- */
646
- ids() {
647
- return this.identifiers.map(identifier => identifier.id);
648
- }
649
-
650
- /**
651
- The link Ember Data will use to fetch or reload this belongs-to
652
- relationship. By default it uses only the "related" resource linkage.
653
- Example
654
- ```javascript
655
- // models/blog.js
656
- import Model, { belongsTo } from '@ember-data/model';
657
- export default Model.extend({
658
- user: belongsTo('user', { async: true, inverse: null })
659
- });
660
- let blog = store.push({
661
- data: {
662
- type: 'blog',
663
- id: 1,
664
- relationships: {
665
- user: {
666
- links: {
667
- related: '/articles/1/author'
668
- }
669
- }
670
- }
671
- }
672
- });
673
- let userRef = blog.belongsTo('user');
674
- // get the identifier of the reference
675
- if (userRef.remoteType() === "link") {
676
- let link = userRef.link();
677
- }
678
- ```
679
- @method link
680
- @public
681
- @return {String} The link Ember Data will use to fetch or reload this belongs-to relationship.
682
- */
683
- link() {
684
- const resource = this._resource();
685
- if (isResourceIdentiferWithRelatedLinks$1(resource)) {
686
- if (resource.links) {
687
- const related = resource.links.related;
688
- return !related || typeof related === 'string' ? related : related.href;
689
- }
690
- }
691
- return null;
692
- }
693
-
694
- /**
695
- * any links that have been received for this relationship
696
- *
697
- * @method links
698
- * @public
699
- * @return
700
- */
701
- links() {
702
- const resource = this._resource();
703
- return resource && resource.links ? resource.links : null;
704
- }
705
-
706
- /**
707
- The meta data for the has-many relationship.
708
- Example
709
- ```javascript
710
- // models/blog.js
711
- import Model, { hasMany } from '@ember-data/model';
712
- export default Model.extend({
713
- users: hasMany('user', { async: true, inverse: null })
714
- });
715
- let blog = store.push({
716
- data: {
717
- type: 'blog',
718
- id: 1,
719
- relationships: {
720
- users: {
721
- links: {
722
- related: {
723
- href: '/articles/1/authors'
724
- },
725
- },
726
- meta: {
727
- lastUpdated: 1458014400000
728
- }
729
- }
730
- }
731
- }
732
- });
733
- let usersRef = blog.hasMany('user');
734
- usersRef.meta() // { lastUpdated: 1458014400000 }
735
- ```
736
- @method meta
737
- @public
738
- @return {Object|null} The meta information for the belongs-to relationship.
739
- */
740
- meta() {
741
- let meta = null;
742
- const resource = this._resource();
743
- if (resource && resource.meta && typeof resource.meta === 'object') {
744
- meta = resource.meta;
745
- }
746
- return meta;
747
- }
748
-
749
- /**
750
- `push` can be used to update the data in the relationship and EmberData
751
- will treat the new data as the canonical value of this relationship on
752
- the backend. An empty array will signify the canonical value should be
753
- empty.
754
- Example model
755
- ```app/models/post.js
756
- import Model, { hasMany } from '@ember-data/model';
757
- export default class PostModel extends Model {
758
- @hasMany('comment', { async: true, inverse: null }) comments;
759
- }
760
- ```
761
- Setup some initial state, note we haven't loaded the comments yet:
762
- ```js
763
- const post = store.push({
764
- data: {
765
- type: 'post',
766
- id: '1',
767
- relationships: {
768
- comments: {
769
- data: [{ type: 'comment', id: '1' }]
770
- }
771
- }
772
- }
773
- });
774
- const commentsRef = post.hasMany('comments');
775
- commentsRef.ids(); // ['1']
776
- ```
777
- Update the state using `push`, note we can do this even without
778
- having loaded these comments yet by providing resource identifiers.
779
- Both full resources and resource identifiers are supported.
780
- ```js
781
- await commentsRef.push({
782
- data: [
783
- { type: 'comment', id: '2' },
784
- { type: 'comment', id: '3' },
785
- ]
786
- });
787
- commentsRef.ids(); // ['2', '3']
788
- ```
789
- For convenience, you can also pass in an array of resources or resource identifiers
790
- without wrapping them in the `data` property:
791
- ```js
792
- await commentsRef.push([
793
- { type: 'comment', id: '4' },
794
- { type: 'comment', id: '5' },
795
- ]);
796
- commentsRef.ids(); // ['4', '5']
797
- ```
798
- When using the `data` property, you may also include other resource data via included,
799
- as well as provide new links and meta to the relationship.
800
- ```js
801
- await commentsRef.push({
802
- links: {
803
- related: '/posts/1/comments'
804
- },
805
- meta: {
806
- total: 2
807
- },
808
- data: [
809
- { type: 'comment', id: '4' },
810
- { type: 'comment', id: '5' },
811
- ],
812
- included: [
813
- { type: 'other-thing', id: '1', attributes: { foo: 'bar' },
814
- ]
815
- });
816
- ```
817
- By default, the store will attempt to fetch any unloaded records before resolving
818
- the returned promise with the ManyArray.
819
- Alternatively, pass `true` as the second argument to avoid fetching unloaded records
820
- and instead the promise will resolve with void without attempting to fetch. This is
821
- particularly useful if you want to update the state of the relationship without
822
- forcing the load of all of the associated records.
823
- @method push
824
- @public
825
- @param {Array|Object} doc a JSONAPI document object describing the new value of this relationship.
826
- @param {Boolean} [skipFetch] if `true`, do not attempt to fetch unloaded records
827
- @return {Promise<ManyArray | void>}
828
- */
829
- async push(doc, skipFetch) {
830
- const {
831
- store
832
- } = this;
833
- const dataDoc = Array.isArray(doc) ? {
834
- data: doc
835
- } : doc;
836
- const isResourceData = Array.isArray(dataDoc.data) && dataDoc.data.length > 0 && isMaybeResource(dataDoc.data[0]);
837
-
838
- // enforce that one of links, meta or data is present
839
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
840
- if (!test) {
841
- throw new Error(`You must provide at least one of 'links', 'meta' or 'data' when calling hasManyReference.push`);
842
- }
843
- })('links' in dataDoc || 'meta' in dataDoc || 'data' in dataDoc) : {};
844
- const identifiers = !Array.isArray(dataDoc.data) ? [] : isResourceData ? store._push(dataDoc, true) : dataDoc.data.map(i => store.identifierCache.getOrCreateRecordIdentifier(i));
845
- const {
846
- identifier
847
- } = this.hasManyRelationship;
848
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
849
- const relationshipMeta = this.hasManyRelationship.definition;
850
- identifiers.forEach(added => {
851
- assertPolymorphicType(identifier, relationshipMeta, added, store);
852
- });
853
- }
854
- const newData = {};
855
- // only set data if it was passed in
856
- if (Array.isArray(dataDoc.data)) {
857
- newData.data = identifiers;
858
- }
859
- if ('links' in dataDoc) {
860
- newData.links = dataDoc.links;
861
- }
862
- if ('meta' in dataDoc) {
863
- newData.meta = dataDoc.meta;
864
- }
865
- store._join(() => {
866
- this.graph.push({
867
- op: 'updateRelationship',
868
- record: identifier,
869
- field: this.key,
870
- value: newData
871
- });
872
- });
873
- if (!skipFetch) return this.load();
874
- }
875
- _isLoaded() {
876
- const hasRelationshipDataProperty = this.hasManyRelationship.state.hasReceivedData;
877
- if (!hasRelationshipDataProperty) {
878
- return false;
879
- }
880
- const relationship = this.graph.getData(this.hasManyRelationship.identifier, this.key);
881
- return relationship.data?.every(identifier => {
882
- return this.store._instanceCache.recordIsLoaded(identifier, true) === true;
883
- });
884
- }
885
-
886
- /**
887
- `value()` synchronously returns the current value of the has-many
888
- relationship. Unlike `record.relationshipName`, calling
889
- `value()` on a reference does not trigger a fetch if the async
890
- relationship is not yet loaded. If the relationship is not loaded
891
- it will always return `null`.
892
- Example
893
- ```app/models/post.js
894
- import Model, { hasMany } from '@ember-data/model';
895
- export default class PostModel extends Model {
896
- @hasMany('comment', { async: true, inverse: null }) comments;
897
- }
898
- ```
899
- ```javascript
900
- let post = store.push({
901
- data: {
902
- type: 'post',
903
- id: 1,
904
- relationships: {
905
- comments: {
906
- data: [{ type: 'comment', id: 1 }]
907
- }
908
- }
909
- }
910
- });
911
- let commentsRef = post.hasMany('comments');
912
- post.comments.then(function(comments) {
913
- commentsRef.value() === comments
914
- })
915
- ```
916
- @method value
917
- @public
918
- @return {ManyArray}
919
- */
920
- value() {
921
- const support = LEGACY_SUPPORT.get(this.___identifier);
922
- if (!ensureRefCanSubscribe(this)) {
923
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
924
- this._ref;
925
- return null;
926
- }
927
- return support.getManyArray(this.key);
928
- }
929
-
930
- /**
931
- Loads the relationship if it is not already loaded. If the
932
- relationship is already loaded this method does not trigger a new
933
- load. This causes a request to the specified
934
- relationship link or reloads all items currently in the relationship.
935
- Example
936
- ```app/models/post.js
937
- import Model, { hasMany } from '@ember-data/model';
938
- export default class PostModel extends Model {
939
- @hasMany('comment', { async: true, inverse: null }) comments;
940
- }
941
- ```
942
- ```javascript
943
- let post = store.push({
944
- data: {
945
- type: 'post',
946
- id: 1,
947
- relationships: {
948
- comments: {
949
- data: [{ type: 'comment', id: 1 }]
950
- }
951
- }
952
- }
953
- });
954
- let commentsRef = post.hasMany('comments');
955
- commentsRef.load().then(function(comments) {
956
- //...
957
- });
958
- ```
959
- You may also pass in an options object whose properties will be
960
- fed forward. This enables you to pass `adapterOptions` into the
961
- request given to the adapter via the reference.
962
- Example
963
- ```javascript
964
- commentsRef.load({ adapterOptions: { isPrivate: true } })
965
- .then(function(comments) {
966
- //...
967
- });
968
- ```
969
- ```app/adapters/comment.js
970
- export default ApplicationAdapter.extend({
971
- findMany(store, type, id, snapshots) {
972
- // In the adapter you will have access to adapterOptions.
973
- let adapterOptions = snapshots[0].adapterOptions;
974
- }
975
- });
976
- ```
977
- @method load
978
- @public
979
- @param {Object} options the options to pass in.
980
- @return {Promise} a promise that resolves with the ManyArray in
981
- this has-many relationship.
982
- */
983
- async load(options) {
984
- const support = LEGACY_SUPPORT.get(this.___identifier);
985
- const fetchSyncRel = !this.hasManyRelationship.definition.isAsync && !areAllInverseRecordsLoaded(this.store, this._resource());
986
- return fetchSyncRel ? support.reloadHasMany(this.key, options) :
987
- // we cast to fix the return type since typescript and eslint don't understand async functions
988
- // properly
989
- support.getHasMany(this.key, options);
990
- }
991
-
992
- /**
993
- Reloads this has-many relationship. This causes a request to the specified
994
- relationship link or reloads all items currently in the relationship.
995
- Example
996
- ```app/models/post.js
997
- import Model, { hasMany } from '@ember-data/model';
998
- export default class PostModel extends Model {
999
- @hasMany('comment', { async: true, inverse: null }) comments;
1000
- }
1001
- ```
1002
- ```javascript
1003
- let post = store.push({
1004
- data: {
1005
- type: 'post',
1006
- id: 1,
1007
- relationships: {
1008
- comments: {
1009
- data: [{ type: 'comment', id: 1 }]
1010
- }
1011
- }
1012
- }
1013
- });
1014
- let commentsRef = post.hasMany('comments');
1015
- commentsRef.reload().then(function(comments) {
1016
- //...
1017
- });
1018
- ```
1019
- You may also pass in an options object whose properties will be
1020
- fed forward. This enables you to pass `adapterOptions` into the
1021
- request given to the adapter via the reference. A full example
1022
- can be found in the `load` method.
1023
- Example
1024
- ```javascript
1025
- commentsRef.reload({ adapterOptions: { isPrivate: true } })
1026
- ```
1027
- @method reload
1028
- @public
1029
- @param {Object} options the options to pass in.
1030
- @return {Promise} a promise that resolves with the ManyArray in this has-many relationship.
1031
- */
1032
- reload(options) {
1033
- const support = LEGACY_SUPPORT.get(this.___identifier);
1034
- return support.reloadHasMany(this.key, options);
1035
- }
1036
- }
1037
- defineNonEnumerableSignal(HasManyReference.prototype, '_ref', 0);
1038
- function isMaybeResource(object) {
1039
- const keys = Object.keys(object).filter(k => k !== 'id' && k !== 'type' && k !== 'lid');
1040
- return keys.length > 0;
1041
- }
1042
- function ensureRefCanSubscribe(rel) {
1043
- const loaded = rel._isLoaded();
1044
- if (!loaded) {
1045
- // subscribe to changes
1046
- // for when we are not loaded yet
1047
- //
1048
- // because the graph optimizes the case where a relationship has never been subscribed,
1049
- // we force accessed to be true here. When we make the graph public we should create a
1050
- // subscribe/unsubscribe API
1051
- const edge = rel.graph.get(rel.___identifier, rel.key);
1052
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1053
- if (!test) {
1054
- throw new Error(`Expected a hasMany relationship for ${rel.___identifier.type}:${rel.key}`);
1055
- }
1056
- })('accessed' in edge) : {};
1057
- edge.accessed = true;
1058
- return false;
1059
- }
1060
- return true;
1061
- }
1062
- function isResourceIdentiferWithRelatedLinks(value) {
1063
- return Boolean(value && value.links && value.links.related);
1064
- }
1065
-
1066
- /**
1067
- A `BelongsToReference` is a low-level API that allows access
1068
- and manipulation of a belongsTo relationship.
1069
-
1070
- It is especially useful when you're dealing with `async` relationships
1071
- from `@ember-data/model` as it allows synchronous access to
1072
- the relationship data if loaded, as well as APIs for loading, reloading
1073
- the data or accessing available information without triggering a load.
1074
-
1075
- It may also be useful when using `sync` relationships with `@ember-data/model`
1076
- that need to be loaded/reloaded with more precise timing than marking the
1077
- relationship as `async` and relying on autofetch would have allowed.
1078
-
1079
- However,keep in mind that marking a relationship as `async: false` will introduce
1080
- bugs into your application if the data is not always guaranteed to be available
1081
- by the time the relationship is accessed. Ergo, it is recommended when using this
1082
- approach to utilize `links` for unloaded relationship state instead of identifiers.
1083
-
1084
- Reference APIs are entangled with the relationship's underlying state,
1085
- thus any getters or cached properties that utilize these will properly
1086
- invalidate if the relationship state changes.
1087
-
1088
- References are "stable", meaning that multiple calls to retrieve the reference
1089
- for a given relationship will always return the same HasManyReference.
1090
-
1091
- @class BelongsToReference
1092
- @public
1093
- */
1094
- class BelongsToReference {
1095
- /**
1096
- * The field name on the parent record for this has-many relationship.
1097
- *
1098
- * @property key
1099
- * @type {String}
1100
- * @public
1101
- */
1102
-
1103
- /**
1104
- * The type of resource this relationship will contain.
1105
- *
1106
- * @property type
1107
- * @type {String}
1108
- * @public
1109
- */
1110
-
1111
- // unsubscribe tokens given to us by the notification manager
1112
-
1113
- constructor(store, graph, parentIdentifier, belongsToRelationship, key) {
1114
- this.graph = graph;
1115
- this.key = key;
1116
- this.belongsToRelationship = belongsToRelationship;
1117
- this.type = belongsToRelationship.definition.type;
1118
- this.store = store;
1119
- this.___identifier = parentIdentifier;
1120
- this.___relatedToken = null;
1121
- this.___token = store.notifications.subscribe(parentIdentifier, (_, bucket, notifiedKey) => {
1122
- if (bucket === 'relationships' && notifiedKey === key) {
1123
- this._ref++;
1124
- }
1125
- });
1126
-
1127
- // TODO inverse
1128
- }
1129
- destroy() {
1130
- // TODO @feature we need the notification manager often enough
1131
- // we should potentially just expose it fully public
1132
- this.store.notifications.unsubscribe(this.___token);
1133
- this.___token = null;
1134
- if (this.___relatedToken) {
1135
- this.store.notifications.unsubscribe(this.___relatedToken);
1136
- this.___relatedToken = null;
1137
- }
1138
- }
1139
-
1140
- /**
1141
- * The identifier of the record that this reference refers to.
1142
- * `null` if no related record is known.
1143
- *
1144
- * @property identifier
1145
- * @type {StableRecordIdentifier | null}
1146
- * @public
1147
- */
1148
- get identifier() {
1149
- if (this.___relatedToken) {
1150
- this.store.notifications.unsubscribe(this.___relatedToken);
1151
- this.___relatedToken = null;
1152
- }
1153
- const resource = this._resource();
1154
- if (resource && resource.data) {
1155
- const identifier = this.store.identifierCache.getOrCreateRecordIdentifier(resource.data);
1156
- this.___relatedToken = this.store.notifications.subscribe(identifier, (_, bucket, notifiedKey) => {
1157
- if (bucket === 'identity' || bucket === 'attributes' && notifiedKey === 'id') {
1158
- this._ref++;
1159
- }
1160
- });
1161
- return identifier;
1162
- }
1163
- return null;
1164
- }
1165
-
1166
- /**
1167
- The `id` of the record that this reference refers to. Together, the
1168
- `type()` and `id()` methods form a composite key for the identity
1169
- map. This can be used to access the id of an async relationship
1170
- without triggering a fetch that would normally happen if you
1171
- attempted to use `record.relationship.id`.
1172
- Example
1173
- ```javascript
1174
- // models/blog.js
1175
- import Model, { belongsTo } from '@ember-data/model';
1176
- export default class BlogModel extends Model {
1177
- @belongsTo('user', { async: true, inverse: null }) user;
1178
- }
1179
- let blog = store.push({
1180
- data: {
1181
- type: 'blog',
1182
- id: 1,
1183
- relationships: {
1184
- user: {
1185
- data: { type: 'user', id: 1 }
1186
- }
1187
- }
1188
- }
1189
- });
1190
- let userRef = blog.belongsTo('user');
1191
- // get the identifier of the reference
1192
- if (userRef.remoteType() === "id") {
1193
- let id = userRef.id();
1194
- }
1195
- ```
1196
- @method id
1197
- @public
1198
- @return {String} The id of the record in this belongsTo relationship.
1199
- */
1200
- static {
1201
- decorateMethodV2(this.prototype, "identifier", [memoized]);
1202
- }
1203
- id() {
1204
- return this.identifier?.id || null;
1205
- }
1206
-
1207
- /**
1208
- The link Ember Data will use to fetch or reload this belongs-to
1209
- relationship. By default it uses only the "related" resource linkage.
1210
- Example
1211
- ```javascript
1212
- // models/blog.js
1213
- import Model, { belongsTo } from '@ember-data/model';
1214
- export default Model.extend({
1215
- user: belongsTo('user', { async: true, inverse: null })
1216
- });
1217
- let blog = store.push({
1218
- data: {
1219
- type: 'blog',
1220
- id: 1,
1221
- relationships: {
1222
- user: {
1223
- links: {
1224
- related: '/articles/1/author'
1225
- }
1226
- }
1227
- }
1228
- }
1229
- });
1230
- let userRef = blog.belongsTo('user');
1231
- // get the identifier of the reference
1232
- if (userRef.remoteType() === "link") {
1233
- let link = userRef.link();
1234
- }
1235
- ```
1236
- @method link
1237
- @public
1238
- @return {String} The link Ember Data will use to fetch or reload this belongs-to relationship.
1239
- */
1240
- link() {
1241
- const resource = this._resource();
1242
- if (isResourceIdentiferWithRelatedLinks(resource)) {
1243
- if (resource.links) {
1244
- const related = resource.links.related;
1245
- return !related || typeof related === 'string' ? related : related.href;
1246
- }
1247
- }
1248
- return null;
1249
- }
1250
-
1251
- /**
1252
- * any links that have been received for this relationship
1253
- *
1254
- * @method links
1255
- * @public
1256
- * @return
1257
- */
1258
- links() {
1259
- const resource = this._resource();
1260
- return resource && resource.links ? resource.links : null;
1261
- }
1262
-
1263
- /**
1264
- The meta data for the belongs-to relationship.
1265
- Example
1266
- ```javascript
1267
- // models/blog.js
1268
- import Model, { belongsTo } from '@ember-data/model';
1269
- export default Model.extend({
1270
- user: belongsTo('user', { async: true, inverse: null })
1271
- });
1272
- let blog = store.push({
1273
- data: {
1274
- type: 'blog',
1275
- id: 1,
1276
- relationships: {
1277
- user: {
1278
- links: {
1279
- related: {
1280
- href: '/articles/1/author'
1281
- },
1282
- },
1283
- meta: {
1284
- lastUpdated: 1458014400000
1285
- }
1286
- }
1287
- }
1288
- }
1289
- });
1290
- let userRef = blog.belongsTo('user');
1291
- userRef.meta() // { lastUpdated: 1458014400000 }
1292
- ```
1293
- @method meta
1294
- @public
1295
- @return {Object} The meta information for the belongs-to relationship.
1296
- */
1297
- meta() {
1298
- let meta = null;
1299
- const resource = this._resource();
1300
- if (resource && resource.meta && typeof resource.meta === 'object') {
1301
- meta = resource.meta;
1302
- }
1303
- return meta;
1304
- }
1305
- _resource() {
1306
- // eslint-disable-next-line @typescript-eslint/no-unused-expressions
1307
- this._ref; // subscribe
1308
- const cache = this.store.cache;
1309
- return cache.getRelationship(this.___identifier, this.key);
1310
- }
1311
-
1312
- /**
1313
- This returns a string that represents how the reference will be
1314
- looked up when it is loaded. If the relationship has a link it will
1315
- use the "link" otherwise it defaults to "id".
1316
- Example
1317
- ```app/models/post.js
1318
- import Model, { hasMany } from '@ember-data/model';
1319
- export default class PostModel extends Model {
1320
- @hasMany('comment', { async: true, inverse: null }) comments;
1321
- }
1322
- ```
1323
- ```javascript
1324
- let post = store.push({
1325
- data: {
1326
- type: 'post',
1327
- id: 1,
1328
- relationships: {
1329
- comments: {
1330
- data: [{ type: 'comment', id: 1 }]
1331
- }
1332
- }
1333
- }
1334
- });
1335
- let commentsRef = post.hasMany('comments');
1336
- // get the identifier of the reference
1337
- if (commentsRef.remoteType() === "ids") {
1338
- let ids = commentsRef.ids();
1339
- } else if (commentsRef.remoteType() === "link") {
1340
- let link = commentsRef.link();
1341
- }
1342
- ```
1343
- @method remoteType
1344
- @public
1345
- @return {String} The name of the remote type. This should either be `link` or `id`
1346
- */
1347
- remoteType() {
1348
- const value = this._resource();
1349
- if (isResourceIdentiferWithRelatedLinks(value)) {
1350
- return 'link';
1351
- }
1352
- return 'id';
1353
- }
1354
-
1355
- /**
1356
- `push` can be used to update the data in the relationship and EmberData
1357
- will treat the new data as the canonical value of this relationship on
1358
- the backend. A value of `null` (e.g. `{ data: null }`) can be passed to
1359
- clear the relationship.
1360
- Example model
1361
- ```app/models/blog.js
1362
- import Model, { belongsTo } from '@ember-data/model';
1363
- export default class BlogModel extends Model {
1364
- @belongsTo('user', { async: true, inverse: null }) user;
1365
- }
1366
- ```
1367
- Setup some initial state, note we haven't loaded the user yet:
1368
- ```js
1369
- const blog = store.push({
1370
- data: {
1371
- type: 'blog',
1372
- id: '1',
1373
- relationships: {
1374
- user: {
1375
- data: { type: 'user', id: '1' }
1376
- }
1377
- }
1378
- }
1379
- });
1380
- const userRef = blog.belongsTo('user');
1381
- userRef.id(); // '1'
1382
- ```
1383
- Update the state using `push`, note we can do this even without
1384
- having loaded the user yet by providing a resource-identifier.
1385
- Both full a resource and a resource-identifier are supported.
1386
- ```js
1387
- await userRef.push({
1388
- data: {
1389
- type: 'user',
1390
- id: '2',
1391
- }
1392
- });
1393
- userRef.id(); // '2'
1394
- ```
1395
- You may also pass in links and meta fore the relationship, and sideload
1396
- additional resources that might be required.
1397
- ```js
1398
- await userRef.push({
1399
- data: {
1400
- type: 'user',
1401
- id: '2',
1402
- },
1403
- links: {
1404
- related: '/articles/1/author'
1405
- },
1406
- meta: {
1407
- lastUpdated: Date.now()
1408
- },
1409
- included: [
1410
- {
1411
- type: 'user-preview',
1412
- id: '2',
1413
- attributes: {
1414
- username: '@runspired'
1415
- }
1416
- }
1417
- ]
1418
- });
1419
- ```
1420
- By default, the store will attempt to fetch the record if it is not loaded or its
1421
- resource data is not included in the call to `push` before resolving the returned
1422
- promise with the new state..
1423
- Alternatively, pass `true` as the second argument to avoid fetching unloaded records
1424
- and instead the promise will resolve with void without attempting to fetch. This is
1425
- particularly useful if you want to update the state of the relationship without
1426
- forcing the load of all of the associated record.
1427
- @method push
1428
- @public
1429
- @param {Object} doc a JSONAPI document object describing the new value of this relationship.
1430
- @param {Boolean} [skipFetch] if `true`, do not attempt to fetch unloaded records
1431
- @return {Promise<OpaqueRecordInstance | null | void>}
1432
- */
1433
- async push(doc, skipFetch) {
1434
- const {
1435
- store
1436
- } = this;
1437
- const isResourceData = doc.data && isMaybeResource(doc.data);
1438
- const added = isResourceData ? store._push(doc, true) : doc.data ? store.identifierCache.getOrCreateRecordIdentifier(doc.data) : null;
1439
- const {
1440
- identifier
1441
- } = this.belongsToRelationship;
1442
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
1443
- if (added) {
1444
- assertPolymorphicType(identifier, this.belongsToRelationship.definition, added, store);
1445
- }
1446
- }
1447
- const newData = {};
1448
-
1449
- // only set data if it was passed in
1450
- if (doc.data || doc.data === null) {
1451
- newData.data = added;
1452
- }
1453
- if ('links' in doc) {
1454
- newData.links = doc.links;
1455
- }
1456
- if ('meta' in doc) {
1457
- newData.meta = doc.meta;
1458
- }
1459
- store._join(() => {
1460
- this.graph.push({
1461
- op: 'updateRelationship',
1462
- record: identifier,
1463
- field: this.key,
1464
- value: newData
1465
- });
1466
- });
1467
- if (!skipFetch) return this.load();
1468
- }
1469
-
1470
- /**
1471
- `value()` synchronously returns the current value of the belongs-to
1472
- relationship. Unlike `record.relationshipName`, calling
1473
- `value()` on a reference does not trigger a fetch if the async
1474
- relationship is not yet loaded. If the relationship is not loaded
1475
- it will always return `null`.
1476
- Example
1477
- ```javascript
1478
- // models/blog.js
1479
- import Model, { belongsTo } from '@ember-data/model';
1480
- export default class BlogModel extends Model {
1481
- @belongsTo('user', { async: true, inverse: null }) user;
1482
- }
1483
- let blog = store.push({
1484
- data: {
1485
- type: 'blog',
1486
- id: 1,
1487
- relationships: {
1488
- user: {
1489
- data: { type: 'user', id: 1 }
1490
- }
1491
- }
1492
- }
1493
- });
1494
- let userRef = blog.belongsTo('user');
1495
- userRef.value(); // null
1496
- // provide data for reference
1497
- userRef.push({
1498
- data: {
1499
- type: 'user',
1500
- id: 1,
1501
- attributes: {
1502
- username: "@user"
1503
- }
1504
- }
1505
- }).then(function(user) {
1506
- userRef.value(); // user
1507
- });
1508
- ```
1509
- @method value
1510
- @public
1511
- @return {Model} the record in this relationship
1512
- */
1513
- value() {
1514
- const resource = this._resource();
1515
- return resource && resource.data ? this.store.peekRecord(resource.data) : null;
1516
- }
1517
-
1518
- /**
1519
- Loads a record in a belongs-to relationship if it is not already
1520
- loaded. If the relationship is already loaded this method does not
1521
- trigger a new load.
1522
- Example
1523
- ```javascript
1524
- // models/blog.js
1525
- import Model, { belongsTo } from '@ember-data/model';
1526
- export default class BlogModel extends Model {
1527
- @belongsTo('user', { async: true, inverse: null }) user;
1528
- }
1529
- let blog = store.push({
1530
- data: {
1531
- type: 'blog',
1532
- id: 1,
1533
- relationships: {
1534
- user: {
1535
- data: { type: 'user', id: 1 }
1536
- }
1537
- }
1538
- }
1539
- });
1540
- let userRef = blog.belongsTo('user');
1541
- userRef.value(); // null
1542
- userRef.load().then(function(user) {
1543
- userRef.value() === user
1544
- });
1545
- ```
1546
- You may also pass in an options object whose properties will be
1547
- fed forward. This enables you to pass `adapterOptions` into the
1548
- request given to the adapter via the reference.
1549
- Example
1550
- ```javascript
1551
- userRef.load({ adapterOptions: { isPrivate: true } }).then(function(user) {
1552
- userRef.value() === user;
1553
- });
1554
- ```
1555
- ```app/adapters/user.js
1556
- import Adapter from '@ember-data/adapter';
1557
- export default class UserAdapter extends Adapter {
1558
- findRecord(store, type, id, snapshot) {
1559
- // In the adapter you will have access to adapterOptions.
1560
- let adapterOptions = snapshot.adapterOptions;
1561
- }
1562
- });
1563
- ```
1564
- @method load
1565
- @public
1566
- @param {Object} options the options to pass in.
1567
- @return {Promise} a promise that resolves with the record in this belongs-to relationship.
1568
- */
1569
- async load(options) {
1570
- const support = LEGACY_SUPPORT.get(this.___identifier);
1571
- const fetchSyncRel = !this.belongsToRelationship.definition.isAsync && !areAllInverseRecordsLoaded(this.store, this._resource());
1572
- return fetchSyncRel ? support.reloadBelongsTo(this.key, options).then(() => this.value()) :
1573
- // we cast to fix the return type since typescript and eslint don't understand async functions
1574
- // properly
1575
- support.getBelongsTo(this.key, options);
1576
- }
1577
-
1578
- /**
1579
- Triggers a reload of the value in this relationship. If the
1580
- remoteType is `"link"` Ember Data will use the relationship link to
1581
- reload the relationship. Otherwise it will reload the record by its
1582
- id.
1583
- Example
1584
- ```javascript
1585
- // models/blog.js
1586
- import Model, { belongsTo } from '@ember-data/model';
1587
- export default class BlogModel extends Model {
1588
- @belongsTo('user', { async: true, inverse: null }) user;
1589
- }
1590
- let blog = store.push({
1591
- data: {
1592
- type: 'blog',
1593
- id: 1,
1594
- relationships: {
1595
- user: {
1596
- data: { type: 'user', id: 1 }
1597
- }
1598
- }
1599
- }
1600
- });
1601
- let userRef = blog.belongsTo('user');
1602
- userRef.reload().then(function(user) {
1603
- userRef.value() === user
1604
- });
1605
- ```
1606
- You may also pass in an options object whose properties will be
1607
- fed forward. This enables you to pass `adapterOptions` into the
1608
- request given to the adapter via the reference. A full example
1609
- can be found in the `load` method.
1610
- Example
1611
- ```javascript
1612
- userRef.reload({ adapterOptions: { isPrivate: true } })
1613
- ```
1614
- @method reload
1615
- @public
1616
- @param {Object} options the options to pass in.
1617
- @return {Promise} a promise that resolves with the record in this belongs-to relationship after the reload has completed.
1618
- */
1619
- reload(options) {
1620
- const support = LEGACY_SUPPORT.get(this.___identifier);
1621
- return support.reloadBelongsTo(this.key, options).then(() => this.value());
1622
- }
1623
- }
1624
- defineNonEnumerableSignal(BelongsToReference.prototype, '_ref', 0);
1625
- const LEGACY_SUPPORT = getOrSetGlobal('LEGACY_SUPPORT', new Map());
1626
- function lookupLegacySupport(record) {
1627
- const identifier = recordIdentifierFor(record);
1628
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1629
- if (!test) {
1630
- throw new Error(`Expected a record`);
1631
- }
1632
- })(identifier) : {};
1633
- let support = LEGACY_SUPPORT.get(identifier);
1634
- if (!support) {
1635
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1636
- if (!test) {
1637
- throw new Error(`Memory Leak Detected`);
1638
- }
1639
- })(!record.isDestroyed && !record.isDestroying) : {};
1640
- support = new LegacySupport(record);
1641
- LEGACY_SUPPORT.set(identifier, support);
1642
- LEGACY_SUPPORT.set(record, support);
1643
- }
1644
- return support;
1645
- }
1646
- class LegacySupport {
1647
- constructor(record) {
1648
- this.record = record;
1649
- this.store = storeFor(record);
1650
- this.identifier = recordIdentifierFor(record);
1651
- this.cache = peekCache(record);
1652
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1653
- const graphFor = importSync('@ember-data/graph/-private').graphFor;
1654
- this.graph = graphFor(this.store);
1655
- }
1656
- this._manyArrayCache = Object.create(null);
1657
- this._relationshipPromisesCache = Object.create(null);
1658
- this._relationshipProxyCache = Object.create(null);
1659
- this._pending = Object.create(null);
1660
- this.references = Object.create(null);
1661
- }
1662
- _syncArray(array) {
1663
- // It’s possible the parent side of the relationship may have been destroyed by this point
1664
- if (this.isDestroyed || this.isDestroying) {
1665
- return;
1666
- }
1667
- const currentState = array[SOURCE];
1668
- const identifier = this.identifier;
1669
- const [identifiers, jsonApi] = this._getCurrentState(identifier, array.key);
1670
- if (jsonApi.meta) {
1671
- array.meta = jsonApi.meta;
1672
- }
1673
- if (jsonApi.links) {
1674
- array.links = jsonApi.links;
1675
- }
1676
- currentState.length = 0;
1677
- fastPush(currentState, identifiers);
1678
- }
1679
- mutate(mutation) {
1680
- this.cache.mutate(mutation);
1681
- }
1682
- _findBelongsTo(key, resource, relationship, options) {
1683
- // TODO @runspired follow up if parent isNew then we should not be attempting load here
1684
- // TODO @runspired follow up on whether this should be in the relationship requests cache
1685
- return this._findBelongsToByJsonApiResource(resource, this.identifier, relationship, options).then(identifier => handleCompletedRelationshipRequest(this, key, relationship, identifier), e => handleCompletedRelationshipRequest(this, key, relationship, null, e));
1686
- }
1687
- reloadBelongsTo(key, options) {
1688
- const loadingPromise = this._relationshipPromisesCache[key];
1689
- if (loadingPromise) {
1690
- return loadingPromise;
1691
- }
1692
- const relationship = this.graph.get(this.identifier, key);
1693
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1694
- if (!test) {
1695
- throw new Error(`Expected ${key} to be a belongs-to relationship`);
1696
- }
1697
- })(isBelongsTo(relationship)) : {};
1698
- const resource = this.cache.getRelationship(this.identifier, key);
1699
- relationship.state.hasFailedLoadAttempt = false;
1700
- relationship.state.shouldForceReload = true;
1701
- const promise = this._findBelongsTo(key, resource, relationship, options);
1702
- if (this._relationshipProxyCache[key]) {
1703
- // @ts-expect-error
1704
- return this._updatePromiseProxyFor('belongsTo', key, {
1705
- promise
1706
- });
1707
- }
1708
- return promise;
1709
- }
1710
- getBelongsTo(key, options) {
1711
- const {
1712
- identifier,
1713
- cache
1714
- } = this;
1715
- const resource = cache.getRelationship(this.identifier, key);
1716
- const relatedIdentifier = resource && resource.data ? resource.data : null;
1717
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1718
- if (!test) {
1719
- throw new Error(`Expected a stable identifier`);
1720
- }
1721
- })(!relatedIdentifier || isStableIdentifier(relatedIdentifier)) : {};
1722
- const store = this.store;
1723
- const relationship = this.graph.get(this.identifier, key);
1724
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1725
- if (!test) {
1726
- throw new Error(`Expected ${key} to be a belongs-to relationship`);
1727
- }
1728
- })(isBelongsTo(relationship)) : {};
1729
- const isAsync = relationship.definition.isAsync;
1730
- const _belongsToState = {
1731
- key,
1732
- store,
1733
- legacySupport: this,
1734
- modelName: relationship.definition.type
1735
- };
1736
- if (isAsync) {
1737
- if (relationship.state.hasFailedLoadAttempt) {
1738
- return this._relationshipProxyCache[key];
1739
- }
1740
- const promise = this._findBelongsTo(key, resource, relationship, options);
1741
- const isLoaded = relatedIdentifier && store._instanceCache.recordIsLoaded(relatedIdentifier);
1742
- return this._updatePromiseProxyFor('belongsTo', key, {
1743
- promise,
1744
- content: isLoaded ? store._instanceCache.getRecord(relatedIdentifier) : null,
1745
- _belongsToState
1746
- });
1747
- } else {
1748
- if (relatedIdentifier === null) {
1749
- return null;
1750
- } else {
1751
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1752
- if (!test) {
1753
- 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> })\`)`);
1754
- }
1755
- })(store._instanceCache.recordIsLoaded(relatedIdentifier, true)) : {};
1756
- return store._instanceCache.getRecord(relatedIdentifier);
1757
- }
1758
- }
1759
- }
1760
- setDirtyBelongsTo(key, value) {
1761
- return this.cache.mutate({
1762
- op: 'replaceRelatedRecord',
1763
- record: this.identifier,
1764
- field: key,
1765
- value: extractIdentifierFromRecord(value)
1766
- },
1767
- // @ts-expect-error
1768
- true);
1769
- }
1770
- _getCurrentState(identifier, field) {
1771
- const jsonApi = this.cache.getRelationship(identifier, field);
1772
- const cache = this.store._instanceCache;
1773
- const identifiers = [];
1774
- if (jsonApi.data) {
1775
- for (let i = 0; i < jsonApi.data.length; i++) {
1776
- const relatedIdentifier = jsonApi.data[i];
1777
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1778
- if (!test) {
1779
- throw new Error(`Expected a stable identifier`);
1780
- }
1781
- })(isStableIdentifier(relatedIdentifier)) : {};
1782
- if (cache.recordIsLoaded(relatedIdentifier, true)) {
1783
- identifiers.push(relatedIdentifier);
1784
- }
1785
- }
1786
- }
1787
- return [identifiers, jsonApi];
1788
- }
1789
- getManyArray(key, definition) {
1790
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1791
- let manyArray = this._manyArrayCache[key];
1792
- if (!definition) {
1793
- definition = this.graph.get(this.identifier, key).definition;
1794
- }
1795
- if (!manyArray) {
1796
- const [identifiers, doc] = this._getCurrentState(this.identifier, key);
1797
- manyArray = new RelatedCollection({
1798
- store: this.store,
1799
- type: definition.type,
1800
- identifier: this.identifier,
1801
- cache: this.cache,
1802
- identifiers,
1803
- key,
1804
- meta: doc.meta || null,
1805
- links: doc.links || null,
1806
- isPolymorphic: definition.isPolymorphic,
1807
- isAsync: definition.isAsync,
1808
- _inverseIsAsync: definition.inverseIsAsync,
1809
- // @ts-expect-error Typescript doesn't have a way for us to thread the generic backwards so it infers unknown instead of T
1810
- manager: this,
1811
- isLoaded: !definition.isAsync,
1812
- allowMutation: true
1813
- });
1814
- this._manyArrayCache[key] = manyArray;
1815
- }
1816
- return manyArray;
1817
- }
1818
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1819
- {
1820
- throw new Error('hasMany only works with the @ember-data/json-api package');
1821
- }
1822
- })() : {};
1823
- }
1824
- fetchAsyncHasMany(key, relationship, manyArray, options) {
1825
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1826
- let loadingPromise = this._relationshipPromisesCache[key];
1827
- if (loadingPromise) {
1828
- return loadingPromise;
1829
- }
1830
- const jsonApi = this.cache.getRelationship(this.identifier, key);
1831
- const promise = this._findHasManyByJsonApiResource(jsonApi, this.identifier, relationship, options);
1832
- if (!promise) {
1833
- manyArray.isLoaded = true;
1834
- return Promise.resolve(manyArray);
1835
- }
1836
- loadingPromise = promise.then(() => handleCompletedRelationshipRequest(this, key, relationship, manyArray), e => handleCompletedRelationshipRequest(this, key, relationship, manyArray, e));
1837
- this._relationshipPromisesCache[key] = loadingPromise;
1838
- return loadingPromise;
1839
- }
1840
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1841
- {
1842
- throw new Error('hasMany only works with the @ember-data/json-api package');
1843
- }
1844
- })() : {};
1845
- }
1846
- reloadHasMany(key, options) {
1847
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1848
- const loadingPromise = this._relationshipPromisesCache[key];
1849
- if (loadingPromise) {
1850
- return loadingPromise;
1851
- }
1852
- const relationship = this.graph.get(this.identifier, key);
1853
- const {
1854
- definition,
1855
- state
1856
- } = relationship;
1857
- state.hasFailedLoadAttempt = false;
1858
- state.shouldForceReload = true;
1859
- const manyArray = this.getManyArray(key, definition);
1860
- const promise = this.fetchAsyncHasMany(key, relationship, manyArray, options);
1861
- if (this._relationshipProxyCache[key]) {
1862
- return this._updatePromiseProxyFor('hasMany', key, {
1863
- promise
1864
- });
1865
- }
1866
- return promise;
1867
- }
1868
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1869
- {
1870
- throw new Error(`hasMany only works with the @ember-data/json-api package`);
1871
- }
1872
- })() : {};
1873
- }
1874
- getHasMany(key, options) {
1875
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1876
- const relationship = this.graph.get(this.identifier, key);
1877
- const {
1878
- definition,
1879
- state
1880
- } = relationship;
1881
- const manyArray = this.getManyArray(key, definition);
1882
- if (definition.isAsync) {
1883
- if (state.hasFailedLoadAttempt) {
1884
- return this._relationshipProxyCache[key];
1885
- }
1886
- const promise = this.fetchAsyncHasMany(key, relationship, manyArray, options);
1887
- return this._updatePromiseProxyFor('hasMany', key, {
1888
- promise,
1889
- content: manyArray
1890
- });
1891
- } else {
1892
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1893
- if (!test) {
1894
- 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> })')`);
1895
- }
1896
- })(!anyUnloaded(this.store, relationship)) : {};
1897
- return manyArray;
1898
- }
1899
- }
1900
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1901
- {
1902
- throw new Error(`hasMany only works with the @ember-data/json-api package`);
1903
- }
1904
- })() : {};
1905
- }
1906
- _updatePromiseProxyFor(kind, key, args) {
1907
- let promiseProxy = this._relationshipProxyCache[key];
1908
- if (kind === 'hasMany') {
1909
- const {
1910
- promise,
1911
- content
1912
- } = args;
1913
- if (promiseProxy) {
1914
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1915
- if (!test) {
1916
- throw new Error(`Expected a PromiseManyArray`);
1917
- }
1918
- })('_update' in promiseProxy) : {};
1919
- promiseProxy._update(promise, content);
1920
- } else {
1921
- promiseProxy = this._relationshipProxyCache[key] = new PromiseManyArray(promise, content);
1922
- }
1923
- return promiseProxy;
1924
- }
1925
- if (promiseProxy) {
1926
- const {
1927
- promise,
1928
- content
1929
- } = args;
1930
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1931
- if (!test) {
1932
- throw new Error(`Expected a PromiseBelongsTo`);
1933
- }
1934
- })('_belongsToState' in promiseProxy) : {};
1935
- if (content !== undefined) {
1936
- promiseProxy.set('content', content);
1937
- }
1938
- void promiseProxy.set('promise', promise);
1939
- } else {
1940
- promiseProxy = PromiseBelongsTo.create(args);
1941
- this._relationshipProxyCache[key] = promiseProxy;
1942
- }
1943
- return promiseProxy;
1944
- }
1945
- referenceFor(kind, name) {
1946
- let reference = this.references[name];
1947
- if (!reference) {
1948
- if (macroCondition(!dependencySatisfies('@ember-data/graph', '*'))) {
1949
- // TODO @runspired while this feels odd, it is not a regression in capability because we do
1950
- // not today support references pulling from RecordDatas other than our own
1951
- // because of the intimate API access involved. This is something we will need to redesign.
1952
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1953
- {
1954
- throw new Error(`snapshot.belongsTo only supported for @ember-data/json-api`);
1955
- }
1956
- })() : {};
1957
- }
1958
- const {
1959
- graph,
1960
- identifier
1961
- } = this;
1962
- const relationship = graph.get(identifier, name);
1963
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
1964
- if (kind) {
1965
- const modelName = identifier.type;
1966
- const actualRelationshipKind = relationship.definition.kind;
1967
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1968
- if (!test) {
1969
- 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.`);
1970
- }
1971
- })(actualRelationshipKind === kind) : {};
1972
- }
1973
- }
1974
- const relationshipKind = relationship.definition.kind;
1975
- if (relationshipKind === 'belongsTo') {
1976
- reference = new BelongsToReference(this.store, graph, identifier, relationship, name);
1977
- } else if (relationshipKind === 'hasMany') {
1978
- reference = new HasManyReference(this.store, graph, identifier, relationship, name);
1979
- }
1980
- this.references[name] = reference;
1981
- }
1982
- return reference;
1983
- }
1984
- _findHasManyByJsonApiResource(resource, parentIdentifier, relationship, options = {}) {
1985
- if (macroCondition(dependencySatisfies('@ember-data/graph', '*'))) {
1986
- if (!resource) {
1987
- return;
1988
- }
1989
- const {
1990
- definition,
1991
- state
1992
- } = relationship;
1993
- upgradeStore(this.store);
1994
- const adapter = this.store.adapterFor?.(definition.type);
1995
- const {
1996
- isStale,
1997
- hasDematerializedInverse,
1998
- hasReceivedData,
1999
- isEmpty,
2000
- shouldForceReload
2001
- } = state;
2002
- const allInverseRecordsAreLoaded = areAllInverseRecordsLoaded(this.store, resource);
2003
- const identifiers = resource.data;
2004
- const shouldFindViaLink = resource.links && resource.links.related && (typeof adapter?.findHasMany === 'function' || typeof identifiers === 'undefined') && (shouldForceReload || hasDematerializedInverse || isStale || !allInverseRecordsAreLoaded && !isEmpty);
2005
- const field = this.store.schema.fields({
2006
- type: definition.inverseType
2007
- }).get(definition.key);
2008
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2009
- if (!test) {
2010
- throw new Error(`Expected a hasMany field definition for ${definition.inverseType}.${definition.key}`);
2011
- }
2012
- })(field && field.kind === 'hasMany') : {};
2013
- const request = {
2014
- useLink: shouldFindViaLink,
2015
- field,
2016
- links: resource.links,
2017
- meta: resource.meta,
2018
- options,
2019
- record: parentIdentifier
2020
- };
2021
-
2022
- // fetch via link
2023
- if (shouldFindViaLink) {
2024
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2025
- if (!test) {
2026
- throw new Error(`Expected collection to be an array`);
2027
- }
2028
- })(!identifiers || Array.isArray(identifiers)) : {};
2029
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2030
- if (!test) {
2031
- throw new Error(`Expected stable identifiers`);
2032
- }
2033
- })(!identifiers || identifiers.every(isStableIdentifier)) : {};
2034
- const req = field.options.linksMode ? {
2035
- url: getRelatedLink(resource),
2036
- op: 'findHasMany',
2037
- method: 'GET',
2038
- records: identifiers || [],
2039
- data: request,
2040
- [EnableHydration]: false
2041
- } : {
2042
- op: 'findHasMany',
2043
- records: identifiers || [],
2044
- data: request,
2045
- cacheOptions: {
2046
- [Symbol.for('wd:skip-cache')]: true
2047
- }
2048
- };
2049
- return this.store.request(req);
2050
- }
2051
- const preferLocalCache = hasReceivedData && !isEmpty;
2052
- const hasLocalPartialData = hasDematerializedInverse || isEmpty && Array.isArray(identifiers) && identifiers.length > 0;
2053
- const attemptLocalCache = !shouldForceReload && !isStale && (preferLocalCache || hasLocalPartialData);
2054
- if (attemptLocalCache && allInverseRecordsAreLoaded) {
2055
- return;
2056
- }
2057
- const hasData = hasReceivedData && !isEmpty;
2058
- if (attemptLocalCache || hasData || hasLocalPartialData) {
2059
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2060
- if (!test) {
2061
- throw new Error(`Expected collection to be an array`);
2062
- }
2063
- })(Array.isArray(identifiers)) : {};
2064
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2065
- if (!test) {
2066
- throw new Error(`Expected stable identifiers`);
2067
- }
2068
- })(identifiers.every(isStableIdentifier)) : {};
2069
- options.reload = options.reload || !attemptLocalCache || undefined;
2070
- return this.store.request({
2071
- op: 'findHasMany',
2072
- records: identifiers,
2073
- data: request,
2074
- cacheOptions: {
2075
- [Symbol.for('wd:skip-cache')]: true
2076
- }
2077
- });
2078
- }
2079
-
2080
- // we were explicitly told we have no data and no links.
2081
- // TODO if the relationshipIsStale, should we hit the adapter anyway?
2082
- return;
2083
- }
2084
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2085
- {
2086
- throw new Error(`hasMany only works with the @ember-data/json-api package`);
2087
- }
2088
- })() : {};
2089
- }
2090
- _findBelongsToByJsonApiResource(resource, parentIdentifier, relationship, options = {}) {
2091
- if (!resource) {
2092
- return Promise.resolve(null);
2093
- }
2094
- const key = relationship.definition.key;
2095
-
2096
- // interleaved promises mean that we MUST cache this here
2097
- // in order to prevent infinite re-render if the request
2098
- // fails.
2099
- if (this._pending[key]) {
2100
- return this._pending[key];
2101
- }
2102
- const identifier = resource.data ? resource.data : null;
2103
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2104
- if (!test) {
2105
- throw new Error(`Expected a stable identifier`);
2106
- }
2107
- })(!identifier || isStableIdentifier(identifier)) : {};
2108
- const {
2109
- isStale,
2110
- hasDematerializedInverse,
2111
- hasReceivedData,
2112
- isEmpty,
2113
- shouldForceReload
2114
- } = relationship.state;
2115
- const allInverseRecordsAreLoaded = areAllInverseRecordsLoaded(this.store, resource);
2116
- const shouldFindViaLink = resource.links?.related && (shouldForceReload || hasDematerializedInverse || isStale || !allInverseRecordsAreLoaded && !isEmpty);
2117
- const field = this.store.schema.fields(this.identifier).get(relationship.definition.key);
2118
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2119
- if (!test) {
2120
- throw new Error(`Attempted to access a belongsTo relationship but no definition exists for it`);
2121
- }
2122
- })(field && field.kind === 'belongsTo') : {};
2123
- const request = {
2124
- useLink: shouldFindViaLink,
2125
- field,
2126
- links: resource.links,
2127
- meta: resource.meta,
2128
- options,
2129
- record: parentIdentifier
2130
- };
2131
-
2132
- // fetch via link
2133
- if (shouldFindViaLink) {
2134
- const req = field.options.linksMode ? {
2135
- url: getRelatedLink(resource),
2136
- op: 'findBelongsTo',
2137
- method: 'GET',
2138
- records: identifier ? [identifier] : [],
2139
- data: request,
2140
- [EnableHydration]: false
2141
- } : {
2142
- op: 'findBelongsTo',
2143
- records: identifier ? [identifier] : [],
2144
- data: request,
2145
- cacheOptions: {
2146
- [Symbol.for('wd:skip-cache')]: true
2147
- }
2148
- };
2149
- const future = this.store.request(req);
2150
- this._pending[key] = future.then(doc => field.options.linksMode ? doc.content.data : doc.content).finally(() => {
2151
- this._pending[key] = undefined;
2152
- });
2153
- return this._pending[key];
2154
- }
2155
- const preferLocalCache = hasReceivedData && allInverseRecordsAreLoaded && !isEmpty;
2156
- const hasLocalPartialData = hasDematerializedInverse || isEmpty && resource.data;
2157
- // null is explicit empty, undefined is "we don't know anything"
2158
- const localDataIsEmpty = !identifier;
2159
- const attemptLocalCache = !shouldForceReload && !isStale && (preferLocalCache || hasLocalPartialData);
2160
-
2161
- // we dont need to fetch and are empty
2162
- if (attemptLocalCache && localDataIsEmpty) {
2163
- return Promise.resolve(null);
2164
- }
2165
-
2166
- // we dont need to fetch because we are local state
2167
- const resourceIsLocal = identifier?.id === null;
2168
- if (attemptLocalCache && allInverseRecordsAreLoaded || resourceIsLocal) {
2169
- return Promise.resolve(identifier);
2170
- }
2171
-
2172
- // we may need to fetch
2173
- if (identifier) {
2174
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2175
- if (!test) {
2176
- throw new Error(`Cannot fetch belongs-to relationship with no information`);
2177
- }
2178
- })(identifier) : {};
2179
- options.reload = options.reload || !attemptLocalCache || undefined;
2180
- this._pending[key] = this.store.request({
2181
- op: 'findBelongsTo',
2182
- records: [identifier],
2183
- data: request,
2184
- cacheOptions: {
2185
- [Symbol.for('wd:skip-cache')]: true
2186
- }
2187
- }).then(doc => doc.content).finally(() => {
2188
- this._pending[key] = undefined;
2189
- });
2190
- return this._pending[key];
2191
- }
2192
-
2193
- // we were explicitly told we have no data and no links.
2194
- // TODO if the relationshipIsStale, should we hit the adapter anyway?
2195
- return Promise.resolve(null);
2196
- }
2197
- destroy() {
2198
- this.isDestroying = true;
2199
- let cache = this._manyArrayCache;
2200
- this._manyArrayCache = Object.create(null);
2201
- Object.keys(cache).forEach(key => {
2202
- cache[key].destroy();
2203
- });
2204
- cache = this._relationshipProxyCache;
2205
- this._relationshipProxyCache = Object.create(null);
2206
- Object.keys(cache).forEach(key => {
2207
- const proxy = cache[key];
2208
- if (proxy.destroy) {
2209
- proxy.destroy();
2210
- }
2211
- });
2212
- cache = this.references;
2213
- this.references = Object.create(null);
2214
- Object.keys(cache).forEach(key => {
2215
- cache[key].destroy();
2216
- });
2217
- this.isDestroyed = true;
2218
- }
2219
- }
2220
- function getRelatedLink(resource) {
2221
- const related = resource.links?.related;
2222
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2223
- if (!test) {
2224
- throw new Error(`Expected a related link`);
2225
- }
2226
- })(related) : {};
2227
- return typeof related === 'object' ? related.href : related;
2228
- }
2229
- function handleCompletedRelationshipRequest(recordExt, key, relationship, value, error) {
2230
- delete recordExt._relationshipPromisesCache[key];
2231
- relationship.state.shouldForceReload = false;
2232
- const isHasMany = relationship.definition.kind === 'hasMany';
2233
- if (isHasMany) {
2234
- // we don't notify the record property here to avoid refetch
2235
- // only the many array
2236
- notifyInternalSignal(value[ARRAY_SIGNAL]);
2237
- }
2238
- if (error) {
2239
- relationship.state.hasFailedLoadAttempt = true;
2240
- const proxy = recordExt._relationshipProxyCache[key];
2241
- // belongsTo relationships are sometimes unloaded
2242
- // when a load fails, in this case we need
2243
- // to make sure that we aren't proxying
2244
- // to destroyed content
2245
- // for the sync belongsTo reload case there will be no proxy
2246
- // for the async reload case there will be no proxy if the ui
2247
- // has never been accessed
2248
- if (proxy && !isHasMany) {
2249
- // @ts-expect-error unsure why this is not resolving the boolean but async belongsTo is weird
2250
- if (proxy.content && proxy.content.isDestroying) {
2251
- proxy.set('content', null);
2252
- }
2253
- recordExt.store.notifications._flush();
2254
- }
2255
- throw error;
2256
- }
2257
- if (isHasMany) {
2258
- value.isLoaded = true;
2259
- } else {
2260
- recordExt.store.notifications._flush();
2261
- }
2262
- relationship.state.hasFailedLoadAttempt = false;
2263
- // only set to not stale if no error is thrown
2264
- relationship.state.isStale = false;
2265
- return isHasMany || !value ? value : recordExt.store.peekRecord(value);
2266
- }
2267
- function extractIdentifierFromRecord(record) {
2268
- if (!record) {
2269
- return null;
2270
- }
2271
- return recordIdentifierFor(record);
2272
- }
2273
- function anyUnloaded(store, relationship) {
2274
- const graph = store._graph;
2275
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2276
- if (!test) {
2277
- throw new Error(`Expected a Graph instance to be available`);
2278
- }
2279
- })(graph) : {};
2280
- const relationshipData = graph.getData(relationship.identifier, relationship.definition.key);
2281
- const state = relationshipData.data;
2282
- const cache = store._instanceCache;
2283
- const unloaded = state?.find(s => {
2284
- const isLoaded = cache.recordIsLoaded(s, true);
2285
- return !isLoaded;
2286
- });
2287
- return unloaded || false;
2288
- }
2289
- function areAllInverseRecordsLoaded(store, resource) {
2290
- const instanceCache = store._instanceCache;
2291
- const identifiers = resource.data;
2292
- if (Array.isArray(identifiers)) {
2293
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2294
- if (!test) {
2295
- throw new Error(`Expected stable identifiers`);
2296
- }
2297
- })(identifiers.every(isStableIdentifier)) : {};
2298
- // treat as collection
2299
- // check for unloaded records
2300
- return identifiers.every(identifier => instanceCache.recordIsLoaded(identifier));
2301
- }
2302
-
2303
- // treat as single resource
2304
- if (!identifiers) return true;
2305
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2306
- if (!test) {
2307
- throw new Error(`Expected stable identifiers`);
2308
- }
2309
- })(isStableIdentifier(identifiers)) : {};
2310
- return instanceCache.recordIsLoaded(identifiers);
2311
- }
2312
- function isBelongsTo(relationship) {
2313
- return relationship.definition.kind === 'belongsTo';
2314
- }
2315
-
2316
- // we force the type here to our own construct because mixin and extend patterns
2317
- // lose generic signatures. We also do this because we need to Omit `clear` from
2318
- // the type of ArrayProxy as we override it's signature.
2319
- const ArrayProxyWithCustomOverrides = ArrayProxy;
2320
-
2321
- /**
2322
- Holds validation errors for a given record, organized by attribute names.
2323
-
2324
- This class is not directly instantiable.
2325
-
2326
- Every `Model` has an `errors` property that is an instance of
2327
- `Errors`. This can be used to display validation error
2328
- messages returned from the server when a `record.save()` rejects.
2329
-
2330
- For Example, if you had a `User` model that looked like this:
2331
-
2332
- ```app/models/user.js
2333
- import Model, { attr } from '@ember-data/model';
2334
-
2335
- export default class UserModel extends Model {
2336
- @attr('string') username;
2337
- @attr('string') email;
2338
- }
2339
- ```
2340
- And you attempted to save a record that did not validate on the backend:
2341
-
2342
- ```javascript
2343
- let user = store.createRecord('user', {
2344
- username: 'tomster',
2345
- email: 'invalidEmail'
2346
- });
2347
- user.save();
2348
- ```
2349
-
2350
- Your backend would be expected to return an error response that described
2351
- the problem, so that error messages can be generated on the app.
2352
-
2353
- API responses will be translated into instances of `Errors` differently,
2354
- depending on the specific combination of adapter and serializer used. You
2355
- may want to check the documentation or the source code of the libraries
2356
- that you are using, to know how they expect errors to be communicated.
2357
-
2358
- Errors can be displayed to the user by accessing their property name
2359
- to get an array of all the error objects for that property. Each
2360
- error object is a JavaScript object with two keys:
2361
-
2362
- - `message` A string containing the error message from the backend
2363
- - `attribute` The name of the property associated with this error message
2364
-
2365
- ```handlebars
2366
- <label>Username: <Input @value={{@model.username}} /> </label>
2367
- {{#each @model.errors.username as |error|}}
2368
- <div class="error">
2369
- {{error.message}}
2370
- </div>
2371
- {{/each}}
2372
-
2373
- <label>Email: <Input @value={{@model.email}} /> </label>
2374
- {{#each @model.errors.email as |error|}}
2375
- <div class="error">
2376
- {{error.message}}
2377
- </div>
2378
- {{/each}}
2379
- ```
2380
-
2381
- You can also access the special `messages` property on the error
2382
- object to get an array of all the error strings.
2383
-
2384
- ```handlebars
2385
- {{#each @model.errors.messages as |message|}}
2386
- <div class="error">
2387
- {{message}}
2388
- </div>
2389
- {{/each}}
2390
- ```
2391
-
2392
- @class Errors
2393
- @public
2394
- @extends Ember.ArrayProxy
2395
- */
2396
- class Errors extends ArrayProxyWithCustomOverrides {
2397
- /**
2398
- @property errorsByAttributeName
2399
- @type {MapWithDefault}
2400
- @private
2401
- */
2402
- get errorsByAttributeName() {
2403
- return new Map();
2404
- }
2405
-
2406
- /**
2407
- Returns errors for a given attribute
2408
- ```javascript
2409
- let user = store.createRecord('user', {
2410
- username: 'tomster',
2411
- email: 'invalidEmail'
2412
- });
2413
- user.save().catch(function(){
2414
- user.errors.errorsFor('email'); // returns:
2415
- // [{attribute: "email", message: "Doesn't look like a valid email."}]
2416
- });
2417
- ```
2418
- @method errorsFor
2419
- @public
2420
- @param {String} attribute
2421
- @return {Array}
2422
- */
2423
- static {
2424
- decorateMethodV2(this.prototype, "errorsByAttributeName", [computed()]);
2425
- }
2426
- errorsFor(attribute) {
2427
- const map = this.errorsByAttributeName;
2428
- let errors = map.get(attribute);
2429
- if (errors === undefined) {
2430
- errors = A();
2431
- map.set(attribute, errors);
2432
- }
2433
-
2434
- // Errors may be a native array with extensions turned on. Since we access
2435
- // the array via a method, and not a computed or using `Ember.get`, it does
2436
- // not entangle properly with autotracking, so we entangle manually by
2437
- // getting the `[]` property.
2438
- get(errors, '[]');
2439
- return errors;
2440
- }
2441
-
2442
- /**
2443
- An array containing all of the error messages for this
2444
- record. This is useful for displaying all errors to the user.
2445
- ```handlebars
2446
- {{#each @model.errors.messages as |message|}}
2447
- <div class="error">
2448
- {{message}}
2449
- </div>
2450
- {{/each}}
2451
- ```
2452
- @property messages
2453
- @public
2454
- @type {Array}
2455
- */
2456
- static {
2457
- decorateFieldV2(this.prototype, "messages", [mapBy('content', 'message')]);
2458
- }
2459
- #messages = (initializeDeferredDecorator(this, "messages"), void 0);
2460
- /**
2461
- @property content
2462
- @type {Array}
2463
- @private
2464
- */
2465
- get content() {
2466
- return A();
2467
- }
2468
-
2469
- /**
2470
- @method unknownProperty
2471
- @private
2472
- */
2473
- static {
2474
- decorateMethodV2(this.prototype, "content", [computed()]);
2475
- }
2476
- unknownProperty(attribute) {
2477
- const errors = this.errorsFor(attribute);
2478
- if (errors.length === 0) {
2479
- return undefined;
2480
- }
2481
- return errors;
2482
- }
2483
-
2484
- /**
2485
- Total number of errors.
2486
- @property length
2487
- @type {Number}
2488
- @public
2489
- @readOnly
2490
- */
2491
-
2492
- /**
2493
- `true` if we have no errors.
2494
- @property isEmpty
2495
- @type {Boolean}
2496
- @public
2497
- @readOnly
2498
- */
2499
- static {
2500
- decorateFieldV2(this.prototype, "isEmpty", [not('length')]);
2501
- }
2502
- #isEmpty = (initializeDeferredDecorator(this, "isEmpty"), void 0);
2503
- /**
2504
- Manually adds errors to the record. This will trigger the `becameInvalid` event/ lifecycle method on
2505
- the record and transition the record into an `invalid` state.
2506
- Example
2507
- ```javascript
2508
- let errors = user.errors;
2509
- // add multiple errors
2510
- errors.add('password', [
2511
- 'Must be at least 12 characters',
2512
- 'Must contain at least one symbol',
2513
- 'Cannot contain your name'
2514
- ]);
2515
- errors.errorsFor('password');
2516
- // =>
2517
- // [
2518
- // { attribute: 'password', message: 'Must be at least 12 characters' },
2519
- // { attribute: 'password', message: 'Must contain at least one symbol' },
2520
- // { attribute: 'password', message: 'Cannot contain your name' },
2521
- // ]
2522
- // add a single error
2523
- errors.add('username', 'This field is required');
2524
- errors.errorsFor('username');
2525
- // =>
2526
- // [
2527
- // { attribute: 'username', message: 'This field is required' },
2528
- // ]
2529
- ```
2530
- @method add
2531
- @public
2532
- @param {String} attribute - the property name of an attribute or relationship
2533
- @param {string[]|string} messages - an error message or array of error messages for the attribute
2534
- */
2535
- add(attribute, messages) {
2536
- const errors = this._findOrCreateMessages(attribute, messages);
2537
- this.addObjects(errors);
2538
- this.errorsFor(attribute).addObjects(errors);
2539
- this.__record.currentState.notify('isValid');
2540
- this.notifyPropertyChange(attribute);
2541
- }
2542
-
2543
- /**
2544
- @method _findOrCreateMessages
2545
- @private
2546
- */
2547
- _findOrCreateMessages(attribute, messages) {
2548
- const errors = this.errorsFor(attribute);
2549
- const messagesArray = Array.isArray(messages) ? messages : [messages];
2550
- const _messages = new Array(messagesArray.length);
2551
- for (let i = 0; i < messagesArray.length; i++) {
2552
- const message = messagesArray[i];
2553
- const err = errors.findBy('message', message);
2554
- if (err) {
2555
- _messages[i] = err;
2556
- } else {
2557
- _messages[i] = {
2558
- attribute: attribute,
2559
- message
2560
- };
2561
- }
2562
- }
2563
- return _messages;
2564
- }
2565
-
2566
- /**
2567
- Manually removes all errors for a given member from the record.
2568
- This will transition the record into a `valid` state, and
2569
- triggers the `becameValid` event and lifecycle method.
2570
- Example:
2571
- ```javascript
2572
- let errors = user.errors;
2573
- errors.add('phone', ['error-1', 'error-2']);
2574
- errors.errorsFor('phone');
2575
- // =>
2576
- // [
2577
- // { attribute: 'phone', message: 'error-1' },
2578
- // { attribute: 'phone', message: 'error-2' },
2579
- // ]
2580
- errors.remove('phone');
2581
- errors.errorsFor('phone');
2582
- // => undefined
2583
- ```
2584
- @method remove
2585
- @public
2586
- @param {String} member - the property name of an attribute or relationship
2587
- */
2588
- remove(attribute) {
2589
- if (this.isEmpty) {
2590
- return;
2591
- }
2592
- const content = this.rejectBy('attribute', attribute);
2593
- this.content.setObjects(content);
2594
-
2595
- // Although errorsByAttributeName.delete is technically enough to sync errors state, we also
2596
- // must mutate the array as well for autotracking
2597
- const errors = this.errorsFor(attribute);
2598
- for (let i = 0; i < errors.length; i++) {
2599
- if (errors[i].attribute === attribute) {
2600
- // .replace from Ember.NativeArray is necessary. JS splice will not work.
2601
- errors.replace(i, 1);
2602
- }
2603
- }
2604
- this.errorsByAttributeName.delete(attribute);
2605
- this.__record.currentState.notify('isValid');
2606
- this.notifyPropertyChange(attribute);
2607
- this.notifyPropertyChange('length');
2608
- }
2609
-
2610
- /**
2611
- Manually clears all errors for the record.
2612
- This will transition the record into a `valid` state, and
2613
- will trigger the `becameValid` event and lifecycle method.
2614
- Example:
2615
- ```javascript
2616
- let errors = user.errors;
2617
- errors.add('username', ['error-a']);
2618
- errors.add('phone', ['error-1', 'error-2']);
2619
- errors.errorsFor('username');
2620
- // =>
2621
- // [
2622
- // { attribute: 'username', message: 'error-a' },
2623
- // ]
2624
- errors.errorsFor('phone');
2625
- // =>
2626
- // [
2627
- // { attribute: 'phone', message: 'error-1' },
2628
- // { attribute: 'phone', message: 'error-2' },
2629
- // ]
2630
- errors.clear();
2631
- errors.errorsFor('username');
2632
- // => undefined
2633
- errors.errorsFor('phone');
2634
- // => undefined
2635
- errors.messages
2636
- // => []
2637
- ```
2638
- @method clear
2639
- @public
2640
- */
2641
- clear() {
2642
- if (this.isEmpty) {
2643
- return;
2644
- }
2645
- const errorsByAttributeName = this.errorsByAttributeName;
2646
- const attributes = [];
2647
- errorsByAttributeName.forEach(function (_, attribute) {
2648
- attributes.push(attribute);
2649
- });
2650
- errorsByAttributeName.clear();
2651
- attributes.forEach(attribute => {
2652
- this.notifyPropertyChange(attribute);
2653
- });
2654
- this.__record.currentState.notify('isValid');
2655
- super.clear();
2656
- }
2657
-
2658
- /**
2659
- Checks if there are error messages for the given attribute.
2660
- ```app/controllers/user/edit.js
2661
- export default class UserEditController extends Controller {
2662
- @action
2663
- save(user) {
2664
- if (user.errors.has('email')) {
2665
- return alert('Please update your email before attempting to save.');
2666
- }
2667
- user.save();
2668
- }
2669
- }
2670
- ```
2671
- @method has
2672
- @public
2673
- @param {String} attribute
2674
- @return {Boolean} true if there some errors on given attribute
2675
- */
2676
- has(attribute) {
2677
- return this.errorsFor(attribute).length > 0;
2678
- }
2679
- }
2680
- function rollbackAttributes() {
2681
- const {
2682
- currentState
2683
- } = this;
2684
- const {
2685
- isNew
2686
- } = currentState;
2687
- this[RecordStore]._join(() => {
2688
- peekCache(this).rollbackAttrs(recordIdentifierFor$1(this));
2689
- this.errors.clear();
2690
- currentState.cleanErrorRequests();
2691
- if (isNew) {
2692
- this.unloadRecord();
2693
- }
2694
- });
2695
- }
2696
- function unloadRecord() {
2697
- if (this.currentState.isNew && (this.isDestroyed || this.isDestroying)) {
2698
- return;
2699
- }
2700
- this[RecordStore].unloadRecord(this);
2701
- }
2702
- function belongsTo(prop) {
2703
- return lookupLegacySupport(this).referenceFor('belongsTo', prop);
2704
- }
2705
- function hasMany(prop) {
2706
- return lookupLegacySupport(this).referenceFor('hasMany', prop);
2707
- }
2708
- function reload(options = {}) {
2709
- options.isReloading = true;
2710
- options.reload = true;
2711
- const identifier = recordIdentifierFor$1(this);
2712
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2713
- if (!test) {
2714
- throw new Error(`You cannot reload a record without an ID`);
2715
- }
2716
- })(identifier.id) : {};
2717
- this.isReloading = true;
2718
- const promise = this[RecordStore].request({
2719
- op: 'findRecord',
2720
- data: {
2721
- options,
2722
- record: identifier
2723
- },
2724
- cacheOptions: {
2725
- [Symbol.for('wd:skip-cache')]: true
2726
- }
2727
- }).then(() => this).finally(() => {
2728
- this.isReloading = false;
2729
- });
2730
- return promise;
2731
- }
2732
- function changedAttributes() {
2733
- return peekCache(this).changedAttrs(recordIdentifierFor$1(this));
2734
- }
2735
- function serialize(options) {
2736
- upgradeStore(this[RecordStore]);
2737
- return this[RecordStore].serializeRecord(this, options);
2738
- }
2739
- function deleteRecord() {
2740
- // ensure we've populated currentState prior to deleting a new record
2741
- if (this.currentState) {
2742
- this[RecordStore].deleteRecord(this);
2743
- }
2744
- }
2745
- function save(options) {
2746
- let promise;
2747
- if (this.currentState.isNew && this.currentState.isDeleted) {
2748
- promise = Promise.resolve(this);
2749
- } else {
2750
- this.errors.clear();
2751
- promise = this[RecordStore].saveRecord(this, options);
2752
- }
2753
- return promise;
2754
- }
2755
- function destroyRecord(options) {
2756
- const {
2757
- isNew
2758
- } = this.currentState;
2759
- this.deleteRecord();
2760
- if (isNew) {
2761
- return Promise.resolve(this);
2762
- }
2763
- return this.save(options).then(_ => {
2764
- this.unloadRecord();
2765
- return this;
2766
- });
2767
- }
2768
- function createSnapshot() {
2769
- const store = this[RecordStore];
2770
- upgradeStore(store);
2771
- if (!store._fetchManager) {
2772
- const FetchManager = importSync('@ember-data/legacy-compat/-private').FetchManager;
2773
- store._fetchManager = new FetchManager(store);
2774
- }
2775
-
2776
- // @ts-expect-error Typescript isn't able to curry narrowed args that are divorced from each other.
2777
- return store._fetchManager.createSnapshot(recordIdentifierFor$1(this));
2778
- }
2779
- function notifyChanges(identifier, value, key, record, store) {
2780
- switch (value) {
2781
- case 'added':
2782
- case 'attributes':
2783
- if (key) {
2784
- notifyAttribute(store, identifier, key, record);
2785
- } else {
2786
- record.eachAttribute(name => {
2787
- notifyAttribute(store, identifier, name, record);
2788
- });
2789
- }
2790
- break;
2791
- case 'relationships':
2792
- if (key) {
2793
- const meta = record.constructor.relationshipsByName.get(key);
2794
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2795
- if (!test) {
2796
- throw new Error(`Expected to find a relationship for ${key} on ${identifier.type}`);
2797
- }
2798
- })(meta) : {};
2799
- notifyRelationship(identifier, key, record, meta);
2800
- } else {
2801
- record.eachRelationship((name, meta) => {
2802
- notifyRelationship(identifier, name, record, meta);
2803
- });
2804
- }
2805
- break;
2806
- case 'identity':
2807
- notifyInternalSignal(peekInternalSignal(withSignalStore(record), 'id'));
2808
- break;
2809
- }
2810
- }
2811
- function notifyRelationship(identifier, key, record, meta) {
2812
- if (meta.kind === 'belongsTo') {
2813
- record.notifyPropertyChange(key);
2814
- } else if (meta.kind === 'hasMany') {
2815
- const support = LEGACY_SUPPORT.get(identifier);
2816
- const manyArray = support && support._manyArrayCache[key];
2817
- const hasPromise = support && support._relationshipPromisesCache[key];
2818
- if (manyArray && hasPromise) {
2819
- // do nothing, we will notify the ManyArray directly
2820
- // once the fetch has completed.
2821
- return;
2822
- }
2823
- if (manyArray) {
2824
- notifyInternalSignal(manyArray[ARRAY_SIGNAL]);
2825
-
2826
- //We need to notifyPropertyChange in the adding case because we need to make sure
2827
- //we fetch the newly added record in case it is unloaded
2828
- //TODO(Igor): Consider whether we could do this only if the record state is unloaded
2829
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2830
- if (!test) {
2831
- throw new Error(`Expected options to exist on relationship meta`);
2832
- }
2833
- })(meta.options) : {};
2834
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
2835
- if (!test) {
2836
- throw new Error(`Expected async to exist on relationship meta options`);
2837
- }
2838
- })('async' in meta.options) : {};
2839
- if (meta.options.async) {
2840
- record.notifyPropertyChange(key);
2841
- }
2842
- }
2843
- }
2844
- }
2845
- function notifyAttribute(store, identifier, key, record) {
2846
- const currentValue = cacheFor(record, key);
2847
- const cache = store.cache;
2848
- if (currentValue !== cache.getAttr(identifier, key)) {
2849
- record.notifyPropertyChange(key);
2850
- }
2851
- }
2852
- const SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/;
2853
- const SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/;
2854
- const PRIMARY_ATTRIBUTE_KEY = 'base';
2855
- function isInvalidError(error) {
2856
- return !!error && error instanceof Error && 'isAdapterError' in error && error.isAdapterError === true && 'code' in error && error.code === 'InvalidError';
2857
- }
2858
-
2859
- /**
2860
- Historically EmberData managed a state machine
2861
- for each record, the localState for which
2862
- was reflected onto Model.
2863
-
2864
- This implements the flags and stateName for backwards compat
2865
- with the state tree that used to be possible (listed below).
2866
-
2867
- stateName and dirtyType are candidates for deprecation.
2868
-
2869
- root
2870
- empty
2871
- deleted // hidden from stateName
2872
- preloaded // hidden from stateName
2873
-
2874
- loading
2875
- empty // hidden from stateName
2876
- preloaded // hidden from stateName
2877
-
2878
- loaded
2879
- saved
2880
- updated
2881
- uncommitted
2882
- invalid
2883
- inFlight
2884
- created
2885
- uncommitted
2886
- invalid
2887
- inFlight
2888
-
2889
- deleted
2890
- saved
2891
- new // hidden from stateName
2892
- uncommitted
2893
- invalid
2894
- inFlight
2895
-
2896
- @internal
2897
- */
2898
- class RecordState {
2899
- constructor(record) {
2900
- const store = storeFor$1(record);
2901
- const identity = recordIdentifierFor(record);
2902
- this.identifier = identity;
2903
- this.record = record;
2904
- this.cache = store.cache;
2905
- this.pendingCount = 0;
2906
- this.fulfilledCount = 0;
2907
- this.rejectedCount = 0;
2908
- this._errorRequests = [];
2909
- this._lastError = null;
2910
- const requests = store.getRequestStateService();
2911
- const notifications = store.notifications;
2912
- const handleRequest = req => {
2913
- if (req.type === 'mutation') {
2914
- switch (req.state) {
2915
- case 'pending':
2916
- this.isSaving = true;
2917
- break;
2918
- case 'rejected':
2919
- this.isSaving = false;
2920
- this._lastError = req;
2921
- if (!(req.response && isInvalidError(req.response.data))) {
2922
- this._errorRequests.push(req);
2923
- }
2924
- notifyErrorsStateChanged(this);
2925
- break;
2926
- case 'fulfilled':
2927
- this._errorRequests = [];
2928
- this._lastError = null;
2929
- this.isSaving = false;
2930
- this.notify('isDirty');
2931
- notifyErrorsStateChanged(this);
2932
- break;
2933
- }
2934
- } else {
2935
- switch (req.state) {
2936
- case 'pending':
2937
- this.pendingCount++;
2938
- this.notify('isLoading');
2939
- break;
2940
- case 'rejected':
2941
- this.pendingCount--;
2942
- this._lastError = req;
2943
- if (!(req.response && isInvalidError(req.response.data))) {
2944
- this._errorRequests.push(req);
2945
- }
2946
- this.notify('isLoading');
2947
- notifyErrorsStateChanged(this);
2948
- break;
2949
- case 'fulfilled':
2950
- this.pendingCount--;
2951
- this.fulfilledCount++;
2952
- this.notify('isLoading');
2953
- this.notify('isDirty');
2954
- notifyErrorsStateChanged(this);
2955
- this._errorRequests = [];
2956
- this._lastError = null;
2957
- break;
2958
- }
2959
- }
2960
- };
2961
- requests.subscribeForRecord(identity, handleRequest);
2962
-
2963
- // we instantiate lazily
2964
- // so we grab anything we don't have yet
2965
- const lastRequest = requests.getLastRequestForRecord(identity);
2966
- if (lastRequest) {
2967
- handleRequest(lastRequest);
2968
- }
2969
- this.handler = notifications.subscribe(identity, (identifier, type, key) => {
2970
- switch (type) {
2971
- case 'state':
2972
- this.notify('isSaved');
2973
- this.notify('isNew');
2974
- this.notify('isDeleted');
2975
- this.notify('isDirty');
2976
- break;
2977
- case 'attributes':
2978
- this.notify('isEmpty');
2979
- this.notify('isDirty');
2980
- break;
2981
- case 'errors':
2982
- this.updateInvalidErrors(this.record.errors);
2983
- this.notify('isValid');
2984
- break;
2985
- }
2986
- });
2987
- }
2988
- destroy() {
2989
- storeFor$1(this.record).notifications.unsubscribe(this.handler);
2990
- }
2991
- notify(key) {
2992
- const signals = withSignalStore(this);
2993
- const signal = peekInternalSignal(signals, key);
2994
- if (signal) {
2995
- notifyInternalSignal(signal);
2996
- }
2997
- }
2998
- updateInvalidErrors(errors) {
2999
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
3000
- if (!test) {
3001
- throw new Error(`Expected the Cache instance for ${this.identifier.lid} to implement getErrors(identifier)`);
3002
- }
3003
- })(typeof this.cache.getErrors === 'function') : {};
3004
- const jsonApiErrors = this.cache.getErrors(this.identifier);
3005
- errors.clear();
3006
- for (let i = 0; i < jsonApiErrors.length; i++) {
3007
- const error = jsonApiErrors[i];
3008
- if (error.source && error.source.pointer) {
3009
- const keyMatch = error.source.pointer.match(SOURCE_POINTER_REGEXP);
3010
- let key;
3011
- if (keyMatch) {
3012
- key = keyMatch[2];
3013
- } else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) {
3014
- key = PRIMARY_ATTRIBUTE_KEY;
3015
- }
3016
- if (key) {
3017
- const errMsg = error.detail || error.title;
3018
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
3019
- if (!test) {
3020
- throw new Error(`Expected field error to have a detail or title to use as the message`);
3021
- }
3022
- })(errMsg) : {};
3023
- errors.add(key, errMsg);
3024
- }
3025
- }
3026
- }
3027
- }
3028
- cleanErrorRequests() {
3029
- this.notify('isValid');
3030
- this.notify('isError');
3031
- this.notify('adapterError');
3032
- this._errorRequests = [];
3033
- this._lastError = null;
3034
- }
3035
- get isLoading() {
3036
- return !this.isLoaded && this.pendingCount > 0 && this.fulfilledCount === 0;
3037
- }
3038
- static {
3039
- decorateMethodV2(this.prototype, "isLoading", [gate]);
3040
- }
3041
- get isLoaded() {
3042
- if (this.isNew) {
3043
- return true;
3044
- }
3045
- return this.fulfilledCount > 0 || !this.isEmpty;
3046
- }
3047
- static {
3048
- decorateMethodV2(this.prototype, "isLoaded", [gate]);
3049
- }
3050
- get isSaved() {
3051
- const rd = this.cache;
3052
- if (this.isDeleted) {
3053
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
3054
- if (!test) {
3055
- throw new Error(`Expected Cache to implement isDeletionCommitted()`);
3056
- }
3057
- })(typeof rd.isDeletionCommitted === 'function') : {};
3058
- return rd.isDeletionCommitted(this.identifier);
3059
- }
3060
- if (this.isNew || this.isEmpty || !this.isValid || this.isDirty || this.isLoading) {
3061
- return false;
3062
- }
3063
- return true;
3064
- }
3065
- static {
3066
- decorateMethodV2(this.prototype, "isSaved", [gate]);
3067
- }
3068
- get isEmpty() {
3069
- const rd = this.cache;
3070
- // TODO this is not actually an RFC'd concept. Determine the
3071
- // correct heuristic to replace this with.
3072
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
3073
- if (!test) {
3074
- throw new Error(`Expected Cache to implement isEmpty()`);
3075
- }
3076
- })(typeof rd.isEmpty === 'function') : {};
3077
- return !this.isNew && rd.isEmpty(this.identifier);
3078
- }
3079
- static {
3080
- decorateMethodV2(this.prototype, "isEmpty", [gate]);
3081
- }
3082
- get isNew() {
3083
- const rd = this.cache;
3084
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
3085
- if (!test) {
3086
- throw new Error(`Expected Cache to implement isNew()`);
3087
- }
3088
- })(typeof rd.isNew === 'function') : {};
3089
- return rd.isNew(this.identifier);
3090
- }
3091
- static {
3092
- decorateMethodV2(this.prototype, "isNew", [gate]);
3093
- }
3094
- get isDeleted() {
3095
- const rd = this.cache;
3096
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
3097
- if (!test) {
3098
- throw new Error(`Expected Cache to implement isDeleted()`);
3099
- }
3100
- })(typeof rd.isDeleted === 'function') : {};
3101
- return rd.isDeleted(this.identifier);
3102
- }
3103
- static {
3104
- decorateMethodV2(this.prototype, "isDeleted", [gate]);
3105
- }
3106
- get isValid() {
3107
- return this.record.errors.length === 0;
3108
- }
3109
- static {
3110
- decorateMethodV2(this.prototype, "isValid", [gate]);
3111
- }
3112
- get isDirty() {
3113
- const rd = this.cache;
3114
- if (this.isEmpty || rd.isDeletionCommitted(this.identifier) || this.isDeleted && this.isNew) {
3115
- return false;
3116
- }
3117
- return this.isDeleted || this.isNew || rd.hasChangedAttrs(this.identifier);
3118
- }
3119
- static {
3120
- decorateMethodV2(this.prototype, "isDirty", [gate]);
3121
- }
3122
- get isError() {
3123
- const errorReq = this._errorRequests[this._errorRequests.length - 1];
3124
- if (!errorReq) {
3125
- return false;
3126
- } else {
3127
- return true;
3128
- }
3129
- }
3130
- static {
3131
- decorateMethodV2(this.prototype, "isError", [gate]);
3132
- }
3133
- get adapterError() {
3134
- const request = this._lastError;
3135
- if (!request) {
3136
- return null;
3137
- }
3138
- return request.state === 'rejected' && request.response.data;
3139
- }
3140
- static {
3141
- decorateMethodV2(this.prototype, "adapterError", [gate]);
3142
- }
3143
- get isPreloaded() {
3144
- return !this.isEmpty && this.isLoading;
3145
- }
3146
- static {
3147
- decorateMethodV2(this.prototype, "isPreloaded", [memoized]);
3148
- }
3149
- get stateName() {
3150
- // we might be empty while loading so check this first
3151
- if (this.isLoading) {
3152
- return 'root.loading';
3153
-
3154
- // got nothing yet or were unloaded
3155
- } else if (this.isEmpty) {
3156
- return 'root.empty';
3157
-
3158
- // deleted substates
3159
- } else if (this.isDeleted) {
3160
- if (this.isSaving) {
3161
- return 'root.deleted.inFlight';
3162
- } else if (this.isSaved) {
3163
- // TODO ensure isSaved isn't true from previous requests
3164
- return 'root.deleted.saved';
3165
- } else if (!this.isValid) {
3166
- return 'root.deleted.invalid';
3167
- } else {
3168
- return 'root.deleted.uncommitted';
3169
- }
3170
-
3171
- // loaded.created substates
3172
- } else if (this.isNew) {
3173
- if (this.isSaving) {
3174
- return 'root.loaded.created.inFlight';
3175
- } else if (!this.isValid) {
3176
- return 'root.loaded.created.invalid';
3177
- }
3178
- return 'root.loaded.created.uncommitted';
3179
-
3180
- // loaded.updated substates
3181
- } else if (this.isSaving) {
3182
- return 'root.loaded.updated.inFlight';
3183
- } else if (!this.isValid) {
3184
- return 'root.loaded.updated.invalid';
3185
- } else if (this.isDirty) {
3186
- return 'root.loaded.updated.uncommitted';
3187
-
3188
- // if nothing remains, we are loaded saved!
3189
- } else {
3190
- return 'root.loaded.saved';
3191
- }
3192
- }
3193
- static {
3194
- decorateMethodV2(this.prototype, "stateName", [memoized]);
3195
- }
3196
- get dirtyType() {
3197
- // we might be empty while loading so check this first
3198
- if (this.isLoading || this.isEmpty) {
3199
- return '';
3200
-
3201
- // deleted substates
3202
- } else if (this.isDirty && this.isDeleted) {
3203
- return 'deleted';
3204
-
3205
- // loaded.created substates
3206
- } else if (this.isNew) {
3207
- return 'created';
3208
-
3209
- // loaded.updated substates
3210
- } else if (this.isSaving || !this.isValid || this.isDirty) {
3211
- return 'updated';
3212
-
3213
- // if nothing remains, we are loaded saved!
3214
- } else {
3215
- return '';
3216
- }
3217
- }
3218
- static {
3219
- decorateMethodV2(this.prototype, "dirtyType", [memoized]);
3220
- }
3221
- }
3222
- defineSignal(RecordState.prototype, 'isSaving', false);
3223
- function notifyErrorsStateChanged(state) {
3224
- state.notify('isValid');
3225
- state.notify('isError');
3226
- state.notify('adapterError');
3227
- }
3228
-
3229
- /**
3230
- @module @ember-data/model
3231
- */
3232
-
3233
- /*
3234
- * This decorator allows us to lazily compute
3235
- * an expensive getter on first-access and thereafter
3236
- * never recompute it.
3237
- */
3238
- function computeOnce(target, propertyName, desc) {
3239
- const cache = new WeakMap();
3240
- // eslint-disable-next-line @typescript-eslint/unbound-method
3241
- const getter = desc.get;
3242
- desc.get = function () {
3243
- let meta = cache.get(this);
3244
- if (!meta) {
3245
- meta = {
3246
- hasComputed: false,
3247
- value: undefined
3248
- };
3249
- cache.set(this, meta);
3250
- }
3251
- if (!meta.hasComputed) {
3252
- meta.value = getter.call(this);
3253
- meta.hasComputed = true;
3254
- }
3255
- return meta.value;
3256
- };
3257
- return desc;
3258
- }
3259
-
3260
- /**
3261
- Base class from which Models can be defined.
3262
-
3263
- ```js
3264
- import Model, { attr } from '@ember-data/model';
3265
-
3266
- export default class User extends Model {
3267
- @attr name;
3268
- }
3269
- ```
3270
-
3271
- Models are used both to define the static schema for a
3272
- particular resource type as well as the class to instantiate
3273
- to present that data from cache.
3274
-
3275
- @class Model
3276
- @public
3277
- @extends Ember.EmberObject
3278
- */
3279
-
3280
- class Model extends EmberObject {
3281
- // set during create by the store
3282
-
3283
- init(options) {
3284
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
3285
- if (!options?._secretInit && !options?._createProps) {
3286
- throw new Error('You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.');
3287
- }
3288
- }
3289
- const createProps = options._createProps;
3290
- const _secretInit = options._secretInit;
3291
- options._createProps = null;
3292
- options._secretInit = null;
3293
- const store = this.store = _secretInit.store;
3294
- super.init(options);
3295
- this[RecordStore] = store;
3296
- const identity = _secretInit.identifier;
3297
- _secretInit.cb(this, _secretInit.cache, identity, _secretInit.store);
3298
- this.___recordState = macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? new RecordState(this) : null;
3299
- this.setProperties(createProps);
3300
- const notifications = store.notifications;
3301
- this.___private_notifications = notifications.subscribe(identity, (identifier, type, field) => {
3302
- notifyChanges(identifier, type, field, this, store);
3303
- });
3304
- }
3305
-
3306
- // @ts-expect-error destroy should not return a value, but ember's types force it to
3307
- destroy() {
3308
- const identifier = recordIdentifierFor$1(this);
3309
- this.___recordState?.destroy();
3310
- const store = storeFor$1(this);
3311
- store.notifications.unsubscribe(this.___private_notifications);
3312
- LEGACY_SUPPORT.get(this)?.destroy();
3313
- LEGACY_SUPPORT.delete(this);
3314
- LEGACY_SUPPORT.delete(identifier);
3315
- super.destroy();
3316
- }
3317
-
3318
- /**
3319
- If this property is `true` the record is in the `empty`
3320
- state. Empty is the first state all records enter after they have
3321
- been created. Most records created by the store will quickly
3322
- transition to the `loading` state if data needs to be fetched from
3323
- the server or the `created` state if the record is created on the
3324
- client. A record can also enter the empty state if the adapter is
3325
- unable to locate the record.
3326
- @property isEmpty
3327
- @public
3328
- @type {Boolean}
3329
- @readOnly
3330
- */
3331
- get isEmpty() {
3332
- return this.currentState.isEmpty;
3333
- }
3334
-
3335
- /**
3336
- If this property is `true` the record is in the `loading` state. A
3337
- record enters this state when the store asks the adapter for its
3338
- data. It remains in this state until the adapter provides the
3339
- requested data.
3340
- @property isLoading
3341
- @public
3342
- @type {Boolean}
3343
- @readOnly
3344
- */
3345
- static {
3346
- decorateMethodV2(this.prototype, "isEmpty", [memoized]);
3347
- }
3348
- get isLoading() {
3349
- return this.currentState.isLoading;
3350
- }
3351
-
3352
- /**
3353
- If this property is `true` the record is in the `loaded` state. A
3354
- record enters this state when its data is populated. Most of a
3355
- record's lifecycle is spent inside substates of the `loaded`
3356
- state.
3357
- Example
3358
- ```javascript
3359
- let record = store.createRecord('model');
3360
- record.isLoaded; // true
3361
- const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));
3362
- model.isLoaded;
3363
- ```
3364
- @property isLoaded
3365
- @public
3366
- @type {Boolean}
3367
- @readOnly
3368
- */
3369
- static {
3370
- decorateMethodV2(this.prototype, "isLoading", [memoized]);
3371
- }
3372
- get isLoaded() {
3373
- return this.currentState.isLoaded;
3374
- }
3375
-
3376
- /**
3377
- If this property is `true` the record is in the `dirty` state. The
3378
- record has local changes that have not yet been saved by the
3379
- adapter. This includes records that have been created (but not yet
3380
- saved) or deleted.
3381
- Example
3382
- ```javascript
3383
- let record = store.createRecord('model');
3384
- record.hasDirtyAttributes; // true
3385
- const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));
3386
- model.hasDirtyAttributes; // false
3387
- model.foo = 'some value';
3388
- model.hasDirtyAttributes; // true
3389
- ```
3390
- @since 1.13.0
3391
- @property hasDirtyAttributes
3392
- @public
3393
- @type {Boolean}
3394
- @readOnly
3395
- */
3396
- static {
3397
- decorateMethodV2(this.prototype, "isLoaded", [memoized]);
3398
- }
3399
- get hasDirtyAttributes() {
3400
- return this.currentState.isDirty;
3401
- }
3402
-
3403
- /**
3404
- If this property is `true` the record is in the `saving` state. A
3405
- record enters the saving state when `save` is called, but the
3406
- adapter has not yet acknowledged that the changes have been
3407
- persisted to the backend.
3408
- Example
3409
- ```javascript
3410
- let record = store.createRecord('model');
3411
- record.isSaving; // false
3412
- let promise = record.save();
3413
- record.isSaving; // true
3414
- promise.then(function() {
3415
- record.isSaving; // false
3416
- });
3417
- ```
3418
- @property isSaving
3419
- @public
3420
- @type {Boolean}
3421
- @readOnly
3422
- */
3423
- static {
3424
- decorateMethodV2(this.prototype, "hasDirtyAttributes", [memoized]);
3425
- }
3426
- get isSaving() {
3427
- return this.currentState.isSaving;
3428
- }
3429
-
3430
- /**
3431
- If this property is `true` the record is in the `deleted` state
3432
- and has been marked for deletion. When `isDeleted` is true and
3433
- `hasDirtyAttributes` is true, the record is deleted locally but the deletion
3434
- was not yet persisted. When `isSaving` is true, the change is
3435
- in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the
3436
- change has persisted.
3437
- Example
3438
- ```javascript
3439
- let record = store.createRecord('model');
3440
- record.isDeleted; // false
3441
- record.deleteRecord();
3442
- // Locally deleted
3443
- record.isDeleted; // true
3444
- record.hasDirtyAttributes; // true
3445
- record.isSaving; // false
3446
- // Persisting the deletion
3447
- let promise = record.save();
3448
- record.isDeleted; // true
3449
- record.isSaving; // true
3450
- // Deletion Persisted
3451
- promise.then(function() {
3452
- record.isDeleted; // true
3453
- record.isSaving; // false
3454
- record.hasDirtyAttributes; // false
3455
- });
3456
- ```
3457
- @property isDeleted
3458
- @public
3459
- @type {Boolean}
3460
- @readOnly
3461
- */
3462
- static {
3463
- decorateMethodV2(this.prototype, "isSaving", [memoized]);
3464
- }
3465
- get isDeleted() {
3466
- return this.currentState.isDeleted;
3467
- }
3468
-
3469
- /**
3470
- If this property is `true` the record is in the `new` state. A
3471
- record will be in the `new` state when it has been created on the
3472
- client and the adapter has not yet report that it was successfully
3473
- saved.
3474
- Example
3475
- ```javascript
3476
- let record = store.createRecord('model');
3477
- record.isNew; // true
3478
- record.save().then(function(model) {
3479
- model.isNew; // false
3480
- });
3481
- ```
3482
- @property isNew
3483
- @public
3484
- @type {Boolean}
3485
- @readOnly
3486
- */
3487
- static {
3488
- decorateMethodV2(this.prototype, "isDeleted", [memoized]);
3489
- }
3490
- get isNew() {
3491
- return this.currentState.isNew;
3492
- }
3493
-
3494
- /**
3495
- If this property is `true` the record is in the `valid` state.
3496
- A record will be in the `valid` state when the adapter did not report any
3497
- server-side validation failures.
3498
- @property isValid
3499
- @public
3500
- @type {Boolean}
3501
- @readOnly
3502
- */
3503
- static {
3504
- decorateMethodV2(this.prototype, "isNew", [memoized]);
3505
- }
3506
- get isValid() {
3507
- return this.currentState.isValid;
3508
- }
3509
-
3510
- /**
3511
- If the record is in the dirty state this property will report what
3512
- kind of change has caused it to move into the dirty
3513
- state. Possible values are:
3514
- - `created` The record has been created by the client and not yet saved to the adapter.
3515
- - `updated` The record has been updated by the client and not yet saved to the adapter.
3516
- - `deleted` The record has been deleted by the client and not yet saved to the adapter.
3517
- Example
3518
- ```javascript
3519
- let record = store.createRecord('model');
3520
- record.dirtyType; // 'created'
3521
- ```
3522
- @property dirtyType
3523
- @public
3524
- @type {String}
3525
- @readOnly
3526
- */
3527
- static {
3528
- decorateMethodV2(this.prototype, "isValid", [memoized]);
3529
- }
3530
- get dirtyType() {
3531
- return this.currentState.dirtyType;
3532
- }
3533
-
3534
- /**
3535
- If `true` the adapter reported that it was unable to save local
3536
- changes to the backend for any reason other than a server-side
3537
- validation error.
3538
- Example
3539
- ```javascript
3540
- record.isError; // false
3541
- record.set('foo', 'valid value');
3542
- record.save().then(null, function() {
3543
- record.isError; // true
3544
- });
3545
- ```
3546
- @property isError
3547
- @public
3548
- @type {Boolean}
3549
- @readOnly
3550
- */
3551
- static {
3552
- decorateMethodV2(this.prototype, "dirtyType", [memoized]);
3553
- }
3554
- get isError() {
3555
- return this.currentState.isError;
3556
- }
3557
- static {
3558
- decorateMethodV2(this.prototype, "isError", [memoized]);
3559
- }
3560
- set isError(v) {
3561
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
3562
- throw new Error(`isError is not directly settable`);
3563
- }
3564
- }
3565
-
3566
- /**
3567
- If `true` the store is attempting to reload the record from the adapter.
3568
- Example
3569
- ```javascript
3570
- record.isReloading; // false
3571
- record.reload();
3572
- record.isReloading; // true
3573
- ```
3574
- @property isReloading
3575
- @public
3576
- @type {Boolean}
3577
- @readOnly
3578
- */
3579
-
3580
- /**
3581
- All ember models have an id property. This is an identifier
3582
- managed by an external source. These are always coerced to be
3583
- strings before being used internally. Note when declaring the
3584
- attributes for a model it is an error to declare an id
3585
- attribute.
3586
- ```javascript
3587
- let record = store.createRecord('model');
3588
- record.id; // null
3589
- const { content: { data: model } } = await store.request(findRecord({ type: 'model', id: '1' }));
3590
- model.id; // '1'
3591
- ```
3592
- @property id
3593
- @public
3594
- @type {String}
3595
- */
3596
- get id() {
3597
- // this guard exists, because some dev-only deprecation code
3598
- // (addListener via validatePropertyInjections) invokes toString before the
3599
- // object is real.
3600
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
3601
- try {
3602
- return recordIdentifierFor$1(this).id;
3603
- } catch {
3604
- return null;
3605
- }
3606
- }
3607
- return recordIdentifierFor$1(this).id;
3608
- }
3609
- static {
3610
- decorateMethodV2(this.prototype, "id", [gate]);
3611
- }
3612
- set id(id) {
3613
- const normalizedId = coerceId(id);
3614
- const identifier = recordIdentifierFor$1(this);
3615
- const didChange = normalizedId !== identifier.id;
3616
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
3617
- if (!test) {
3618
- throw new Error(`Cannot set ${identifier.type} record's id to ${id}, because id is already ${identifier.id}`);
3619
- }
3620
- })(!didChange || identifier.id === null) : {};
3621
- if (normalizedId !== null && didChange) {
3622
- this.store._instanceCache.setRecordId(identifier, normalizedId);
3623
- this.store.notifications.notify(identifier, 'identity');
3624
- }
3625
- }
3626
- toString() {
3627
- return `<model::${this.constructor.modelName}:${this.id}>`;
3628
- }
3629
-
3630
- /**
3631
- @property currentState
3632
- @private
3633
- @type {Object}
3634
- */
3635
- // TODO we can probably make this a computeOnce
3636
- // we likely do not need to notify the currentState root anymore
3637
- get currentState() {
3638
- // descriptors are called with the wrong `this` context during mergeMixins
3639
- // when using legacy/classic ember classes. Basically: lazy in prod and eager in dev.
3640
- // so we do this to try to steer folks to the nicer "dont user currentState"
3641
- // error.
3642
- if (macroCondition(!getGlobalConfig().WarpDrive.env.DEBUG)) {
3643
- if (!this.___recordState) {
3644
- this.___recordState = new RecordState(this);
3645
- }
3646
- }
3647
- return this.___recordState;
3648
- }
3649
- static {
3650
- decorateMethodV2(this.prototype, "currentState", [gate]);
3651
- }
3652
- set currentState(_v) {
3653
- throw new Error('cannot set currentState');
3654
- }
3655
-
3656
- /**
3657
- The store service instance which created this record instance
3658
- @property store
3659
- @public
3660
- */
3661
-
3662
- /**
3663
- When the record is in the `invalid` state this object will contain
3664
- any errors returned by the adapter. When present the errors hash
3665
- contains keys corresponding to the invalid property names
3666
- and values which are arrays of Javascript objects with two keys:
3667
- - `message` A string containing the error message from the backend
3668
- - `attribute` The name of the property associated with this error message
3669
- ```javascript
3670
- record.errors.length; // 0
3671
- record.set('foo', 'invalid value');
3672
- record.save().catch(function() {
3673
- record.errors.foo;
3674
- // [{message: 'foo should be a number.', attribute: 'foo'}]
3675
- });
3676
- ```
3677
- The `errors` property is useful for displaying error messages to
3678
- the user.
3679
- ```handlebars
3680
- <label>Username: <Input @value={{@model.username}} /> </label>
3681
- {{#each @model.errors.username as |error|}}
3682
- <div class="error">
3683
- {{error.message}}
3684
- </div>
3685
- {{/each}}
3686
- <label>Email: <Input @value={{@model.email}} /> </label>
3687
- {{#each @model.errors.email as |error|}}
3688
- <div class="error">
3689
- {{error.message}}
3690
- </div>
3691
- {{/each}}
3692
- ```
3693
- You can also access the special `messages` property on the error
3694
- object to get an array of all the error strings.
3695
- ```handlebars
3696
- {{#each @model.errors.messages as |message|}}
3697
- <div class="error">
3698
- {{message}}
3699
- </div>
3700
- {{/each}}
3701
- ```
3702
- @property errors
3703
- @public
3704
- @type {Errors}
3705
- */
3706
- get errors() {
3707
- const errors = Errors.create({
3708
- __record: this
3709
- });
3710
- this.currentState.updateInvalidErrors(errors);
3711
- return errors;
3712
- }
3713
-
3714
- /**
3715
- This property holds the `AdapterError` object with which
3716
- last adapter operation was rejected.
3717
- @property adapterError
3718
- @public
3719
- @type {AdapterError}
3720
- */
3721
- static {
3722
- decorateMethodV2(this.prototype, "errors", [computeOnce]);
3723
- }
3724
- get adapterError() {
3725
- return this.currentState.adapterError;
3726
- }
3727
- static {
3728
- decorateMethodV2(this.prototype, "adapterError", [memoized]);
3729
- }
3730
- set adapterError(v) {
3731
- throw new Error(`adapterError is not directly settable`);
3732
- }
3733
-
3734
- /**
3735
- Create a JSON representation of the record, using the serialization
3736
- strategy of the store's adapter.
3737
- `serialize` takes an optional hash as a parameter, currently
3738
- supported options are:
3739
- - `includeId`: `true` if the record's ID should be included in the
3740
- JSON representation.
3741
- @method serialize
3742
- @public
3743
- @param {Object} options
3744
- @return {Object} an object whose values are primitive JSON values only
3745
- */
3746
- /*
3747
- We hook the default implementation to ensure
3748
- our tagged properties are properly notified
3749
- as well. We still super for everything because
3750
- sync observers require a direct call occuring
3751
- to trigger their flush. We wouldn't need to
3752
- super in 4.0+ where sync observers are removed.
3753
- */
3754
- // @ts-expect-error no return is necessary, but Ember's types are forcing it
3755
- notifyPropertyChange(prop) {
3756
- const signals = withSignalStore(this);
3757
- entangleSignal(signals, this, prop, undefined);
3758
- super.notifyPropertyChange(prop);
3759
- }
3760
-
3761
- /**
3762
- Marks the record as deleted but does not save it. You must call
3763
- `save` afterwards if you want to persist it. You might use this
3764
- method if you want to allow the user to still `rollbackAttributes()`
3765
- after a delete was made.
3766
- Example
3767
- ```js
3768
- import Component from '@glimmer/component';
3769
- export default class extends Component {
3770
- softDelete = () => {
3771
- this.args.model.deleteRecord();
3772
- }
3773
- confirm = () => {
3774
- this.args.model.save();
3775
- }
3776
- undo = () => {
3777
- this.args.model.rollbackAttributes();
3778
- }
3779
- }
3780
- ```
3781
- @method deleteRecord
3782
- @public
3783
- */
3784
-
3785
- /**
3786
- Same as `deleteRecord`, but saves the record immediately.
3787
- Example
3788
- ```js
3789
- import Component from '@glimmer/component';
3790
- export default class extends Component {
3791
- delete = () => {
3792
- this.args.model.destroyRecord().then(function() {
3793
- this.transitionToRoute('model.index');
3794
- });
3795
- }
3796
- }
3797
- ```
3798
- If you pass an object on the `adapterOptions` property of the options
3799
- argument it will be passed to your adapter via the snapshot
3800
- ```js
3801
- record.destroyRecord({ adapterOptions: { subscribe: false } });
3802
- ```
3803
- ```app/adapters/post.js
3804
- import MyCustomAdapter from './custom-adapter';
3805
- export default class PostAdapter extends MyCustomAdapter {
3806
- deleteRecord(store, type, snapshot) {
3807
- if (snapshot.adapterOptions.subscribe) {
3808
- // ...
3809
- }
3810
- // ...
3811
- }
3812
- }
3813
- ```
3814
- @method destroyRecord
3815
- @public
3816
- @param {Object} options
3817
- @return {Promise} a promise that will be resolved when the adapter returns
3818
- successfully or rejected if the adapter returns with an error.
3819
- */
3820
-
3821
- /**
3822
- Unloads the record from the store. This will not send a delete request
3823
- to your server, it just unloads the record from memory.
3824
- @method unloadRecord
3825
- @public
3826
- */
3827
-
3828
- /**
3829
- Returns an object, whose keys are changed properties, and value is
3830
- an [oldProp, newProp] array.
3831
- The array represents the diff of the canonical state with the local state
3832
- of the model. Note: if the model is created locally, the canonical state is
3833
- empty since the adapter hasn't acknowledged the attributes yet:
3834
- Example
3835
- ```app/models/mascot.js
3836
- import Model, { attr } from '@ember-data/model';
3837
- export default class MascotModel extends Model {
3838
- @attr('string') name;
3839
- @attr('boolean', {
3840
- defaultValue: false
3841
- })
3842
- isAdmin;
3843
- }
3844
- ```
3845
- ```javascript
3846
- let mascot = store.createRecord('mascot');
3847
- mascot.changedAttributes(); // {}
3848
- mascot.set('name', 'Tomster');
3849
- mascot.changedAttributes(); // { name: [undefined, 'Tomster'] }
3850
- mascot.set('isAdmin', true);
3851
- mascot.changedAttributes(); // { isAdmin: [undefined, true], name: [undefined, 'Tomster'] }
3852
- mascot.save().then(function() {
3853
- mascot.changedAttributes(); // {}
3854
- mascot.set('isAdmin', false);
3855
- mascot.changedAttributes(); // { isAdmin: [true, false] }
3856
- });
3857
- ```
3858
- @method changedAttributes
3859
- @public
3860
- @return {Object} an object, whose keys are changed properties,
3861
- and value is an [oldProp, newProp] array.
3862
- */
3863
-
3864
- /**
3865
- If the model `hasDirtyAttributes` this function will discard any unsaved
3866
- changes. If the model `isNew` it will be removed from the store.
3867
- Example
3868
- ```javascript
3869
- record.name; // 'Untitled Document'
3870
- record.set('name', 'Doc 1');
3871
- record.name; // 'Doc 1'
3872
- record.rollbackAttributes();
3873
- record.name; // 'Untitled Document'
3874
- ```
3875
- @since 1.13.0
3876
- @method rollbackAttributes
3877
- @public
3878
- */
3879
-
3880
- /**
3881
- @method _createSnapshot
3882
- @private
3883
- */
3884
- // TODO @deprecate in favor of a public API or examples of how to test successfully
3885
-
3886
- /**
3887
- Save the record and persist any changes to the record to an
3888
- external source via the adapter.
3889
- Example
3890
- ```javascript
3891
- record.set('name', 'Tomster');
3892
- record.save().then(function() {
3893
- // Success callback
3894
- }, function() {
3895
- // Error callback
3896
- });
3897
- ```
3898
- If you pass an object using the `adapterOptions` property of the options
3899
- argument it will be passed to your adapter via the snapshot.
3900
- ```js
3901
- record.save({ adapterOptions: { subscribe: false } });
3902
- ```
3903
- ```app/adapters/post.js
3904
- import MyCustomAdapter from './custom-adapter';
3905
- export default class PostAdapter extends MyCustomAdapter {
3906
- updateRecord(store, type, snapshot) {
3907
- if (snapshot.adapterOptions.subscribe) {
3908
- // ...
3909
- }
3910
- // ...
3911
- }
3912
- }
3913
- ```
3914
- @method save
3915
- @public
3916
- @param {Object} options
3917
- @return {Promise} a promise that will be resolved when the adapter returns
3918
- successfully or rejected if the adapter returns with an error.
3919
- */
3920
-
3921
- /**
3922
- Reload the record from the adapter.
3923
- This will only work if the record has already finished loading.
3924
- Example
3925
- ```js
3926
- import Component from '@glimmer/component';
3927
- export default class extends Component {
3928
- async reload = () => {
3929
- await this.args.model.reload();
3930
- // do something with the reloaded model
3931
- }
3932
- }
3933
- ```
3934
- @method reload
3935
- @public
3936
- @param {Object} options optional, may include `adapterOptions` hash which will be passed to adapter request
3937
- @return {Promise} a promise that will be resolved with the record when the
3938
- adapter returns successfully or rejected if the adapter returns
3939
- with an error.
3940
- */
3941
-
3942
- attr() {
3943
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
3944
- {
3945
- throw new Error('The `attr` method is not available on Model, a Snapshot was probably expected. Are you passing a Model instead of a Snapshot to your serializer?');
3946
- }
3947
- })() : {};
3948
- }
3949
-
3950
- /**
3951
- Get the reference for the specified belongsTo relationship.
3952
- For instance, given the following model
3953
- ```app/models/blog-post.js
3954
- import Model, { belongsTo } from '@ember-data/model';
3955
- export default class BlogPost extends Model {
3956
- @belongsTo('user', { async: true, inverse: null }) author;
3957
- }
3958
- ```
3959
- Then the reference for the author relationship would be
3960
- retrieved from a record instance like so:
3961
- ```js
3962
- blogPost.belongsTo('author');
3963
- ```
3964
- A `BelongsToReference` is a low-level API that allows access
3965
- and manipulation of a belongsTo relationship.
3966
- It is especially useful when you're dealing with `async` relationships
3967
- as it allows synchronous access to the relationship data if loaded, as
3968
- well as APIs for loading, reloading the data or accessing available
3969
- information without triggering a load.
3970
- It may also be useful when using `sync` relationships that need to be
3971
- loaded/reloaded with more precise timing than marking the
3972
- relationship as `async` and relying on autofetch would have allowed.
3973
- However,keep in mind that marking a relationship as `async: false` will introduce
3974
- bugs into your application if the data is not always guaranteed to be available
3975
- by the time the relationship is accessed. Ergo, it is recommended when using this
3976
- approach to utilize `links` for unloaded relationship state instead of identifiers.
3977
- Reference APIs are entangled with the relationship's underlying state,
3978
- thus any getters or cached properties that utilize these will properly
3979
- invalidate if the relationship state changes.
3980
- References are "stable", meaning that multiple calls to retrieve the reference
3981
- for a given relationship will always return the same HasManyReference.
3982
- @method belongsTo
3983
- @public
3984
- @param {String} name of the relationship
3985
- @since 2.5.0
3986
- @return {BelongsToReference} reference for this relationship
3987
- */
3988
-
3989
- /**
3990
- Get the reference for the specified hasMany relationship.
3991
- For instance, given the following model
3992
- ```app/models/blog-post.js
3993
- import Model, { hasMany } from '@ember-data/model';
3994
- export default class BlogPost extends Model {
3995
- @hasMany('comment', { async: true, inverse: null }) comments;
3996
- }
3997
- ```
3998
- Then the reference for the comments relationship would be
3999
- retrieved from a record instance like so:
4000
- ```js
4001
- blogPost.hasMany('comments');
4002
- ```
4003
- A `HasManyReference` is a low-level API that allows access
4004
- and manipulation of a hasMany relationship.
4005
- It is especially useful when you are dealing with `async` relationships
4006
- as it allows synchronous access to the relationship data if loaded, as
4007
- well as APIs for loading, reloading the data or accessing available
4008
- information without triggering a load.
4009
- It may also be useful when using `sync` relationships with `@ember-data/model`
4010
- that need to be loaded/reloaded with more precise timing than marking the
4011
- relationship as `async` and relying on autofetch would have allowed.
4012
- However,keep in mind that marking a relationship as `async: false` will introduce
4013
- bugs into your application if the data is not always guaranteed to be available
4014
- by the time the relationship is accessed. Ergo, it is recommended when using this
4015
- approach to utilize `links` for unloaded relationship state instead of identifiers.
4016
- Reference APIs are entangled with the relationship's underlying state,
4017
- thus any getters or cached properties that utilize these will properly
4018
- invalidate if the relationship state changes.
4019
- References are "stable", meaning that multiple calls to retrieve the reference
4020
- for a given relationship will always return the same HasManyReference.
4021
- @method hasMany
4022
- @public
4023
- @param {String} name of the relationship
4024
- @since 2.5.0
4025
- @return {HasManyReference} reference for this relationship
4026
- */
4027
-
4028
- /**
4029
- Given a callback, iterates over each of the relationships in the model,
4030
- invoking the callback with the name of each relationship and its relationship
4031
- descriptor.
4032
- The callback method you provide should have the following signature (all
4033
- parameters are optional):
4034
- ```javascript
4035
- function(name, descriptor);
4036
- ```
4037
- - `name` the name of the current property in the iteration
4038
- - `descriptor` the meta object that describes this relationship
4039
- The relationship descriptor argument is an object with the following properties.
4040
- - **name** <span class="type">String</span> the name of this relationship on the Model
4041
- - **kind** <span class="type">String</span> "hasMany" or "belongsTo"
4042
- - **options** <span class="type">Object</span> the original options hash passed when the relationship was declared
4043
- - **parentType** <span class="type">Model</span> the type of the Model that owns this relationship
4044
- - **type** <span class="type">String</span> the type name of the related Model
4045
- Note that in addition to a callback, you can also pass an optional target
4046
- object that will be set as `this` on the context.
4047
- Example
4048
- ```app/serializers/application.js
4049
- import JSONSerializer from '@ember-data/serializer/json';
4050
- export default class ApplicationSerializer extends JSONSerializer {
4051
- serialize(record, options) {
4052
- let json = {};
4053
- record.eachRelationship(function(name, descriptor) {
4054
- if (descriptor.kind === 'hasMany') {
4055
- let serializedHasManyName = name.toUpperCase() + '_IDS';
4056
- json[serializedHasManyName] = record.get(name).map(r => r.id);
4057
- }
4058
- });
4059
- return json;
4060
- }
4061
- }
4062
- ```
4063
- @method eachRelationship
4064
- @public
4065
- @param {Function} callback the callback to invoke
4066
- @param {any} binding the value to which the callback's `this` should be bound
4067
- */
4068
- eachRelationship(callback, binding) {
4069
- this.constructor.eachRelationship(callback, binding);
4070
- }
4071
- relationshipFor(name) {
4072
- return this.constructor.relationshipsByName.get(name);
4073
- }
4074
- inverseFor(name) {
4075
- return this.constructor.inverseFor(name, storeFor$1(this));
4076
- }
4077
- eachAttribute(callback, binding) {
4078
- this.constructor.eachAttribute(callback, binding);
4079
- }
4080
- static isModel = true;
4081
-
4082
- /**
4083
- Create should only ever be called by the store. To create an instance of a
4084
- `Model` in a dirty state use `store.createRecord`.
4085
- To create instances of `Model` in a clean state, use `store.push`
4086
- @method create
4087
- @private
4088
- @static
4089
- */
4090
-
4091
- /**
4092
- Represents the model's class name as a string. This can be used to look up the model's class name through
4093
- `Store`'s modelFor method.
4094
- `modelName` is generated for you by EmberData. It will be a lowercased, dasherized string.
4095
- For example:
4096
- ```javascript
4097
- store.modelFor('post').modelName; // 'post'
4098
- store.modelFor('blog-post').modelName; // 'blog-post'
4099
- ```
4100
- The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload
4101
- keys to underscore (instead of dasherized), you might use the following code:
4102
- ```javascript
4103
- import RESTSerializer from '@ember-data/serializer/rest';
4104
- import { underscore } from '<app-name>/utils/string-utils';
4105
- export default const PostSerializer = RESTSerializer.extend({
4106
- payloadKeyFromModelName(modelName) {
4107
- return underscore(modelName);
4108
- }
4109
- });
4110
- ```
4111
- @property modelName
4112
- @public
4113
- @type String
4114
- @readonly
4115
- @static
4116
- */
4117
- static modelName = null;
4118
-
4119
- /*
4120
- These class methods below provide relationship
4121
- introspection abilities about relationships.
4122
- A note about the computed properties contained here:
4123
- **These properties are effectively sealed once called for the first time.**
4124
- To avoid repeatedly doing expensive iteration over a model's fields, these
4125
- values are computed once and then cached for the remainder of the runtime of
4126
- your application.
4127
- If your application needs to modify a class after its initial definition
4128
- (for example, using `reopen()` to add additional attributes), make sure you
4129
- do it before using your model with the store, which uses these properties
4130
- extensively.
4131
- */
4132
-
4133
- /**
4134
- For a given relationship name, returns the model type of the relationship.
4135
- For example, if you define a model like this:
4136
- ```app/models/post.js
4137
- import Model, { hasMany } from '@ember-data/model';
4138
- export default class PostModel extends Model {
4139
- @hasMany('comment') comments;
4140
- }
4141
- ```
4142
- Calling `store.modelFor('post').typeForRelationship('comments', store)` will return `Comment`.
4143
- @method typeForRelationship
4144
- @public
4145
- @static
4146
- @param {String} name the name of the relationship
4147
- @param {store} store an instance of Store
4148
- @return {Model} the type of the relationship, or undefined
4149
- */
4150
- static typeForRelationship(name, store) {
4151
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4152
- if (!test) {
4153
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4154
- }
4155
- })(this.modelName) : {};
4156
- const relationship = this.relationshipsByName.get(name);
4157
- return relationship && store.modelFor(relationship.type);
4158
- }
4159
- static get inverseMap() {
4160
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4161
- if (!test) {
4162
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4163
- }
4164
- })(this.modelName) : {};
4165
- return Object.create(null);
4166
- }
4167
-
4168
- /**
4169
- Find the relationship which is the inverse of the one asked for.
4170
- For example, if you define models like this:
4171
- ```app/models/post.js
4172
- import Model, { hasMany } from '@ember-data/model';
4173
- export default class PostModel extends Model {
4174
- @hasMany('message') comments;
4175
- }
4176
- ```
4177
- ```app/models/message.js
4178
- import Model, { belongsTo } from '@ember-data/model';
4179
- export default class MessageModel extends Model {
4180
- @belongsTo('post') owner;
4181
- }
4182
- ```
4183
- ``` js
4184
- store.modelFor('post').inverseFor('comments', store) // { type: 'message', name: 'owner', kind: 'belongsTo' }
4185
- store.modelFor('message').inverseFor('owner', store) // { type: 'post', name: 'comments', kind: 'hasMany' }
4186
- ```
4187
- @method inverseFor
4188
- @public
4189
- @static
4190
- @param {String} name the name of the relationship
4191
- @param {Store} store
4192
- @return {Object} the inverse relationship, or null
4193
- */
4194
- static {
4195
- decorateMethodV2(this, "inverseMap", [computeOnce]);
4196
- }
4197
- static inverseFor(name, store) {
4198
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4199
- if (!test) {
4200
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4201
- }
4202
- })(this.modelName) : {};
4203
- const inverseMap = this.inverseMap;
4204
- if (inverseMap[name]) {
4205
- return inverseMap[name];
4206
- } else {
4207
- const inverse = this._findInverseFor(name, store);
4208
- inverseMap[name] = inverse;
4209
- return inverse;
4210
- }
4211
- }
4212
-
4213
- //Calculate the inverse, ignoring the cache
4214
- static _findInverseFor(name, store) {
4215
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4216
- if (!test) {
4217
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4218
- }
4219
- })(this.modelName) : {};
4220
- const relationship = this.relationshipsByName.get(name);
4221
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4222
- if (!test) {
4223
- throw new Error(`No relationship named '${name}' on '${this.modelName}' exists.`);
4224
- }
4225
- })(relationship) : {};
4226
- if (!relationship) {
4227
- return null;
4228
- }
4229
- const {
4230
- options
4231
- } = relationship;
4232
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4233
- if (!test) {
4234
- throw new Error(`Expected the relationship ${name} on ${this.modelName} to define an inverse.`);
4235
- }
4236
- })(options.inverse === null || typeof options.inverse === 'string' && options.inverse.length > 0) : {};
4237
- if (options.inverse === null) {
4238
- return null;
4239
- }
4240
- const schemaExists = store.schema.hasResource(relationship);
4241
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4242
- if (!test) {
4243
- throw new Error(`No associated schema found for '${relationship.type}' while calculating the inverse of ${name} on ${this.modelName}`);
4244
- }
4245
- })(schemaExists) : {};
4246
- if (!schemaExists) {
4247
- return null;
4248
- }
4249
- const inverseField = store.schema.fields(relationship).get(options.inverse);
4250
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4251
- if (!test) {
4252
- throw new Error(`No inverse relationship found for '${name}' on '${this.modelName}'`);
4253
- }
4254
- })(inverseField && (inverseField.kind === 'belongsTo' || inverseField.kind === 'hasMany')) : {};
4255
- return inverseField || null;
4256
- }
4257
-
4258
- /**
4259
- The model's relationships as a map, keyed on the type of the
4260
- relationship. The value of each entry is an array containing a descriptor
4261
- for each relationship with that type, describing the name of the relationship
4262
- as well as the type.
4263
- For example, given the following model definition:
4264
- ```app/models/blog.js
4265
- import Model, { belongsTo, hasMany } from '@ember-data/model';
4266
- export default class BlogModel extends Model {
4267
- @hasMany('user') users;
4268
- @belongsTo('user') owner;
4269
- @hasMany('post') posts;
4270
- }
4271
- ```
4272
- This computed property would return a map describing these
4273
- relationships, like this:
4274
- ```javascript
4275
- import Blog from 'app/models/blog';
4276
- import User from 'app/models/user';
4277
- import Post from 'app/models/post';
4278
- let relationships = Blog.relationships;
4279
- relationships.user;
4280
- //=> [ { name: 'users', kind: 'hasMany' },
4281
- // { name: 'owner', kind: 'belongsTo' } ]
4282
- relationships.post;
4283
- //=> [ { name: 'posts', kind: 'hasMany' } ]
4284
- ```
4285
- @property relationships
4286
- @public
4287
- @static
4288
- @type Map
4289
- @readOnly
4290
- */
4291
-
4292
- static get relationships() {
4293
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4294
- if (!test) {
4295
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4296
- }
4297
- })(this.modelName) : {};
4298
- const map = new Map();
4299
- const relationshipsByName = this.relationshipsByName;
4300
-
4301
- // Loop through each computed property on the class
4302
- relationshipsByName.forEach(desc => {
4303
- const {
4304
- type
4305
- } = desc;
4306
- if (!map.has(type)) {
4307
- map.set(type, []);
4308
- }
4309
- map.get(type).push(desc);
4310
- });
4311
- return map;
4312
- }
4313
-
4314
- /**
4315
- A hash containing lists of the model's relationships, grouped
4316
- by the relationship kind. For example, given a model with this
4317
- definition:
4318
- ```app/models/blog.js
4319
- import Model, { belongsTo, hasMany } from '@ember-data/model';
4320
- export default class BlogModel extends Model {
4321
- @hasMany('user') users;
4322
- @belongsTo('user') owner;
4323
- @hasMany('post') posts;
4324
- }
4325
- ```
4326
- This property would contain the following:
4327
- ```javascript
4328
- import Blog from 'app/models/blog';
4329
- let relationshipNames = Blog.relationshipNames;
4330
- relationshipNames.hasMany;
4331
- //=> ['users', 'posts']
4332
- relationshipNames.belongsTo;
4333
- //=> ['owner']
4334
- ```
4335
- @property relationshipNames
4336
- @public
4337
- @static
4338
- @type Object
4339
- @readOnly
4340
- */
4341
- static {
4342
- decorateMethodV2(this, "relationships", [computeOnce]);
4343
- }
4344
- static get relationshipNames() {
4345
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4346
- if (!test) {
4347
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4348
- }
4349
- })(this.modelName) : {};
4350
- const names = {
4351
- hasMany: [],
4352
- belongsTo: []
4353
- };
4354
- this.eachComputedProperty((name, meta) => {
4355
- if (isRelationshipSchema(meta)) {
4356
- names[meta.kind].push(name);
4357
- }
4358
- });
4359
- return names;
4360
- }
4361
-
4362
- /**
4363
- An array of types directly related to a model. Each type will be
4364
- included once, regardless of the number of relationships it has with
4365
- the model.
4366
- For example, given a model with this definition:
4367
- ```app/models/blog.js
4368
- import Model, { belongsTo, hasMany } from '@ember-data/model';
4369
- export default class BlogModel extends Model {
4370
- @hasMany('user') users;
4371
- @belongsTo('user') owner;
4372
- @hasMany('post') posts;
4373
- }
4374
- ```
4375
- This property would contain the following:
4376
- ```javascript
4377
- import Blog from 'app/models/blog';
4378
- let relatedTypes = Blog.relatedTypes');
4379
- //=> ['user', 'post']
4380
- ```
4381
- @property relatedTypes
4382
- @public
4383
- @static
4384
- @type Array
4385
- @readOnly
4386
- */
4387
- static {
4388
- decorateMethodV2(this, "relationshipNames", [computeOnce]);
4389
- }
4390
- static get relatedTypes() {
4391
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4392
- if (!test) {
4393
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4394
- }
4395
- })(this.modelName) : {};
4396
- const types = [];
4397
- const rels = this.relationshipsObject;
4398
- const relationships = Object.keys(rels);
4399
-
4400
- // create an array of the unique types involved
4401
- // in relationships
4402
- for (let i = 0; i < relationships.length; i++) {
4403
- const name = relationships[i];
4404
- const meta = rels[name];
4405
- const modelName = meta.type;
4406
- if (!types.includes(modelName)) {
4407
- types.push(modelName);
4408
- }
4409
- }
4410
- return types;
4411
- }
4412
-
4413
- /**
4414
- A map whose keys are the relationships of a model and whose values are
4415
- relationship descriptors.
4416
- For example, given a model with this
4417
- definition:
4418
- ```app/models/blog.js
4419
- import Model, { belongsTo, hasMany } from '@ember-data/model';
4420
- export default class BlogModel extends Model {
4421
- @hasMany('user') users;
4422
- @belongsTo('user') owner;
4423
- @hasMany('post') posts;
4424
- }
4425
- ```
4426
- This property would contain the following:
4427
- ```javascript
4428
- import Blog from 'app/models/blog';
4429
- let relationshipsByName = Blog.relationshipsByName;
4430
- relationshipsByName.users;
4431
- //=> { name: 'users', kind: 'hasMany', type: 'user', options: Object }
4432
- relationshipsByName.owner;
4433
- //=> { name: 'owner', kind: 'belongsTo', type: 'user', options: Object }
4434
- ```
4435
- @property relationshipsByName
4436
- @public
4437
- @static
4438
- @type Map
4439
- @readOnly
4440
- */
4441
- static {
4442
- decorateMethodV2(this, "relatedTypes", [computeOnce]);
4443
- }
4444
- static get relationshipsByName() {
4445
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4446
- if (!test) {
4447
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4448
- }
4449
- })(this.modelName) : {};
4450
- const map = new Map();
4451
- const rels = this.relationshipsObject;
4452
- const relationships = Object.keys(rels);
4453
- for (let i = 0; i < relationships.length; i++) {
4454
- const name = relationships[i];
4455
- const value = rels[name];
4456
- map.set(value.name, value);
4457
- }
4458
- return map;
4459
- }
4460
- static {
4461
- decorateMethodV2(this, "relationshipsByName", [computeOnce]);
4462
- }
4463
- static get relationshipsObject() {
4464
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4465
- if (!test) {
4466
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4467
- }
4468
- })(this.modelName) : {};
4469
- const relationships = Object.create(null);
4470
- const modelName = this.modelName;
4471
- this.eachComputedProperty((name, meta) => {
4472
- if (!isRelationshipSchema(meta)) {
4473
- return;
4474
- }
4475
- // TODO deprecate key being here
4476
- meta.key = name;
4477
- meta.name = name;
4478
- relationships[name] = meta;
4479
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4480
- if (!test) {
4481
- throw new Error(`Expected options in meta`);
4482
- }
4483
- })(meta.options && typeof meta.options === 'object') : {};
4484
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4485
- if (!test) {
4486
- throw new Error(`You should not specify both options.as and options.inverse as null on ${modelName}.${meta.name}, as if there is no inverse field there is no abstract type to conform to. You may have intended for this relationship to be polymorphic, or you may have mistakenly set inverse to null.`);
4487
- }
4488
- })(!(meta.options.inverse === null && meta.options.as?.length)) : {};
4489
- });
4490
- return relationships;
4491
- }
4492
-
4493
- /**
4494
- A map whose keys are the fields of the model and whose values are strings
4495
- describing the kind of the field. A model's fields are the union of all of its
4496
- attributes and relationships.
4497
- For example:
4498
- ```app/models/blog.js
4499
- import Model, { attr, belongsTo, hasMany } from '@ember-data/model';
4500
- export default class BlogModel extends Model {
4501
- @hasMany('user') users;
4502
- @belongsTo('user') owner;
4503
- @hasMany('post') posts;
4504
- @attr('string') title;
4505
- }
4506
- ```
4507
- ```js
4508
- import Blog from 'app/models/blog'
4509
- let fields = Blog.fields;
4510
- fields.forEach(function(kind, field) {
4511
- // do thing
4512
- });
4513
- // prints:
4514
- // users, hasMany
4515
- // owner, belongsTo
4516
- // posts, hasMany
4517
- // title, attribute
4518
- ```
4519
- @property fields
4520
- @public
4521
- @static
4522
- @type Map
4523
- @readOnly
4524
- */
4525
- static {
4526
- decorateMethodV2(this, "relationshipsObject", [computeOnce]);
4527
- }
4528
- static get fields() {
4529
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4530
- if (!test) {
4531
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4532
- }
4533
- })(this.modelName) : {};
4534
- const map = new Map();
4535
- this.eachComputedProperty((name, meta) => {
4536
- if (isRelationshipSchema(meta)) {
4537
- map.set(name, meta.kind);
4538
- } else if (isAttributeSchema(meta)) {
4539
- map.set(name, 'attribute');
4540
- }
4541
- });
4542
- return map;
4543
- }
4544
-
4545
- /**
4546
- Given a callback, iterates over each of the relationships in the model,
4547
- invoking the callback with the name of each relationship and its relationship
4548
- descriptor.
4549
- @method eachRelationship
4550
- @public
4551
- @static
4552
- @param {Function} callback the callback to invoke
4553
- @param {any} binding the value to which the callback's `this` should be bound
4554
- */
4555
- static {
4556
- decorateMethodV2(this, "fields", [computeOnce]);
4557
- }
4558
- static eachRelationship(callback, binding) {
4559
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4560
- if (!test) {
4561
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4562
- }
4563
- })(this.modelName) : {};
4564
- this.relationshipsByName.forEach((relationship, name) => {
4565
- callback.call(binding, name, relationship);
4566
- });
4567
- }
4568
-
4569
- /**
4570
- Given a callback, iterates over each of the types related to a model,
4571
- invoking the callback with the related type's class. Each type will be
4572
- returned just once, regardless of how many different relationships it has
4573
- with a model.
4574
- @method eachRelatedType
4575
- @public
4576
- @static
4577
- @param {Function} callback the callback to invoke
4578
- @param {any} binding the value to which the callback's `this` should be bound
4579
- */
4580
- static eachRelatedType(callback, binding) {
4581
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4582
- if (!test) {
4583
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4584
- }
4585
- })(this.modelName) : {};
4586
- const relationshipTypes = this.relatedTypes;
4587
- for (let i = 0; i < relationshipTypes.length; i++) {
4588
- const type = relationshipTypes[i];
4589
- callback.call(binding, type);
4590
- }
4591
- }
4592
-
4593
- /**
4594
- *
4595
- * @method determineRelationshipType
4596
- * @private
4597
- * @deprecated
4598
- */
4599
- static determineRelationshipType(knownSide, store) {
4600
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4601
- if (!test) {
4602
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4603
- }
4604
- })(this.modelName) : {};
4605
- const knownKey = knownSide.name;
4606
- const knownKind = knownSide.kind;
4607
- const inverse = this.inverseFor(knownKey, store);
4608
- // let key;
4609
-
4610
- if (!inverse) {
4611
- return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone';
4612
- }
4613
-
4614
- // key = inverse.name;
4615
- const otherKind = inverse.kind;
4616
- if (otherKind === 'belongsTo') {
4617
- return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne';
4618
- } else {
4619
- return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany';
4620
- }
4621
- }
4622
-
4623
- /**
4624
- A map whose keys are the attributes of the model (properties
4625
- described by attr) and whose values are the meta object for the
4626
- property.
4627
- Example
4628
- ```app/models/person.js
4629
- import Model, { attr } from '@ember-data/model';
4630
- export default class PersonModel extends Model {
4631
- @attr('string') firstName;
4632
- @attr('string') lastName;
4633
- @attr('date') birthday;
4634
- }
4635
- ```
4636
- ```javascript
4637
- import Person from 'app/models/person'
4638
- let attributes = Person.attributes
4639
- attributes.forEach(function(meta, name) {
4640
- // do thing
4641
- });
4642
- // prints:
4643
- // firstName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "firstName"}
4644
- // lastName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "lastName"}
4645
- // birthday {type: "date", kind: 'attribute', options: Object, parentType: function, name: "birthday"}
4646
- ```
4647
- @property attributes
4648
- @public
4649
- @static
4650
- @type {Map}
4651
- @readOnly
4652
- */
4653
- static get attributes() {
4654
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4655
- if (!test) {
4656
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4657
- }
4658
- })(this.modelName) : {};
4659
- const map = new Map();
4660
- this.eachComputedProperty((name, meta) => {
4661
- if (isAttributeSchema(meta)) {
4662
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4663
- if (!test) {
4664
- throw new Error("You may not set 'id' as an attribute on your model. Please remove any lines that look like: `id: attr('<type>')` from " + this.toString());
4665
- }
4666
- })(name !== 'id') : {};
4667
-
4668
- // TODO deprecate key being here
4669
- meta.key = name;
4670
- meta.name = name;
4671
- map.set(name, meta);
4672
- }
4673
- });
4674
- return map;
4675
- }
4676
-
4677
- /**
4678
- A map whose keys are the attributes of the model (properties
4679
- described by attr) and whose values are type of transformation
4680
- applied to each attribute. This map does not include any
4681
- attributes that do not have an transformation type.
4682
- Example
4683
- ```app/models/person.js
4684
- import Model, { attr } from '@ember-data/model';
4685
- export default class PersonModel extends Model {
4686
- @attr firstName;
4687
- @attr('string') lastName;
4688
- @attr('date') birthday;
4689
- }
4690
- ```
4691
- ```javascript
4692
- import Person from 'app/models/person';
4693
- let transformedAttributes = Person.transformedAttributes
4694
- transformedAttributes.forEach(function(field, type) {
4695
- // do thing
4696
- });
4697
- // prints:
4698
- // lastName string
4699
- // birthday date
4700
- ```
4701
- @property transformedAttributes
4702
- @public
4703
- @static
4704
- @type {Map}
4705
- @readOnly
4706
- */
4707
- static {
4708
- decorateMethodV2(this, "attributes", [computeOnce]);
4709
- }
4710
- static get transformedAttributes() {
4711
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4712
- if (!test) {
4713
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4714
- }
4715
- })(this.modelName) : {};
4716
- const map = new Map();
4717
- this.eachAttribute((name, meta) => {
4718
- if (meta.type) {
4719
- map.set(name, meta.type);
4720
- }
4721
- });
4722
- return map;
4723
- }
4724
-
4725
- /**
4726
- Iterates through the attributes of the model, calling the passed function on each
4727
- attribute.
4728
- The callback method you provide should have the following signature (all
4729
- parameters are optional):
4730
- ```javascript
4731
- function(name, meta);
4732
- ```
4733
- - `name` the name of the current property in the iteration
4734
- - `meta` the meta object for the attribute property in the iteration
4735
- Note that in addition to a callback, you can also pass an optional target
4736
- object that will be set as `this` on the context.
4737
- Example
4738
- ```javascript
4739
- import Model, { attr } from '@ember-data/model';
4740
- class PersonModel extends Model {
4741
- @attr('string') firstName;
4742
- @attr('string') lastName;
4743
- @attr('date') birthday;
4744
- }
4745
- PersonModel.eachAttribute(function(name, meta) {
4746
- // do thing
4747
- });
4748
- // prints:
4749
- // firstName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "firstName"}
4750
- // lastName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "lastName"}
4751
- // birthday {type: "date", kind: 'attribute', options: Object, parentType: function, name: "birthday"}
4752
- ```
4753
- @method eachAttribute
4754
- @public
4755
- @param {Function} callback The callback to execute
4756
- @param {Object} [binding] the value to which the callback's `this` should be bound
4757
- @static
4758
- */
4759
- static {
4760
- decorateMethodV2(this, "transformedAttributes", [computeOnce]);
4761
- }
4762
- static eachAttribute(callback, binding) {
4763
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4764
- if (!test) {
4765
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4766
- }
4767
- })(this.modelName) : {};
4768
- this.attributes.forEach((meta, name) => {
4769
- callback.call(binding, name, meta);
4770
- });
4771
- }
4772
-
4773
- /**
4774
- Iterates through the transformedAttributes of the model, calling
4775
- the passed function on each attribute. Note the callback will not be
4776
- called for any attributes that do not have an transformation type.
4777
- The callback method you provide should have the following signature (all
4778
- parameters are optional):
4779
- ```javascript
4780
- function(name, type);
4781
- ```
4782
- - `name` the name of the current property in the iteration
4783
- - `type` a string containing the name of the type of transformed
4784
- applied to the attribute
4785
- Note that in addition to a callback, you can also pass an optional target
4786
- object that will be set as `this` on the context.
4787
- Example
4788
- ```javascript
4789
- import Model, { attr } from '@ember-data/model';
4790
- let Person = Model.extend({
4791
- firstName: attr(),
4792
- lastName: attr('string'),
4793
- birthday: attr('date')
4794
- });
4795
- Person.eachTransformedAttribute(function(name, type) {
4796
- // do thing
4797
- });
4798
- // prints:
4799
- // lastName string
4800
- // birthday date
4801
- ```
4802
- @method eachTransformedAttribute
4803
- @public
4804
- @param {Function} callback The callback to execute
4805
- @param {Object} [binding] the value to which the callback's `this` should be bound
4806
- @static
4807
- */
4808
- static eachTransformedAttribute(callback, binding) {
4809
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4810
- if (!test) {
4811
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4812
- }
4813
- })(this.modelName) : {};
4814
- this.transformedAttributes.forEach((type, name) => {
4815
- callback.call(binding, name, type);
4816
- });
4817
- }
4818
-
4819
- /**
4820
- Returns the name of the model class.
4821
- @method toString
4822
- @public
4823
- @static
4824
- */
4825
- static toString() {
4826
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
4827
- if (!test) {
4828
- throw new Error(`Accessing schema information on Models without looking up the model via the store is disallowed.`);
4829
- }
4830
- })(this.modelName) : {};
4831
- return `model:${this.modelName}`;
4832
- }
4833
- }
4834
-
4835
- // @ts-expect-error TS doesn't know how to do `this` function overloads
4836
- Model.prototype.save = save;
4837
- // @ts-expect-error TS doesn't know how to do `this` function overloads
4838
- Model.prototype.destroyRecord = destroyRecord;
4839
- Model.prototype.unloadRecord = unloadRecord;
4840
- Model.prototype.hasMany = hasMany;
4841
- Model.prototype.belongsTo = belongsTo;
4842
- Model.prototype.serialize = serialize;
4843
- Model.prototype._createSnapshot = createSnapshot;
4844
- Model.prototype.deleteRecord = deleteRecord;
4845
- Model.prototype.changedAttributes = changedAttributes;
4846
- Model.prototype.rollbackAttributes = rollbackAttributes;
4847
- Model.prototype.reload = reload;
4848
- defineSignal(Model.prototype, 'isReloading', false);
4849
-
4850
- // this is required to prevent `init` from passing
4851
- // the values initialized during create to `setUnknownProperty`
4852
- Model.prototype._createProps = null;
4853
- Model.prototype._secretInit = null;
4854
- if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
4855
- const lookupDescriptor = function lookupDescriptor(obj, keyName) {
4856
- let current = obj;
4857
- do {
4858
- const descriptor = Object.getOwnPropertyDescriptor(current, keyName);
4859
- if (descriptor !== undefined) {
4860
- return descriptor;
4861
- }
4862
- current = Object.getPrototypeOf(current);
4863
- } while (current !== null);
4864
- return null;
4865
- };
4866
-
4867
- // eslint-disable-next-line @typescript-eslint/unbound-method
4868
- const init = Model.prototype.init;
4869
- Model.prototype.init = function (createArgs) {
4870
- init.call(this, createArgs);
4871
- const ourDescriptor = lookupDescriptor(Model.prototype, 'currentState');
4872
- const theirDescriptor = lookupDescriptor(this, 'currentState');
4873
- if (!ourDescriptor || !theirDescriptor) {
4874
- throw new Error(`Unable to determine if 'currentState' is a reserved property name on instances of classes extending Model. Please ensure that 'currentState' is not defined as a property on ${this.constructor.toString()}`);
4875
- }
4876
- const realState = this.___recordState;
4877
- if (ourDescriptor.get !== theirDescriptor.get || realState !== this.currentState) {
4878
- throw new Error(`'currentState' is a reserved property name on instances of classes extending Model. Please choose a different property name for ${this.constructor.toString()}`);
4879
- }
4880
- const ID_DESCRIPTOR = lookupDescriptor(Model.prototype, 'id');
4881
- const idDesc = lookupDescriptor(this, 'id');
4882
- if (!ID_DESCRIPTOR || !idDesc) {
4883
- throw new Error(`Unable to determine if 'id' is a reserved property name on instances of classes extending Model. Please ensure that 'id' is not defined as a property on ${this.constructor.toString()}`);
4884
- }
4885
- if (idDesc.get !== ID_DESCRIPTOR.get) {
4886
- throw new Error(`You may not set 'id' as an attribute on your model. Please remove any lines that look like: \`id: attr('<type>')\` from ${this.constructor.toString()}`);
4887
- }
4888
- };
4889
- delete Model.reopen;
4890
- delete Model.reopenClass;
4891
- }
4892
- function isRelationshipSchema(meta) {
4893
- const hasKind = typeof meta === 'object' && meta !== null && 'kind' in meta && 'options' in meta;
4894
- return hasKind && (meta.kind === 'hasMany' || meta.kind === 'belongsTo');
4895
- }
4896
- function isAttributeSchema(meta) {
4897
- return typeof meta === 'object' && meta !== null && 'kind' in meta && meta.kind === 'attribute';
4898
- }
4899
- export { Errors as E, LEGACY_SUPPORT as L, Model as M, PromiseBelongsTo as P, RecordState as R, PromiseManyArray as a, save as b, reload as c, destroyRecord as d, deleteRecord as e, changedAttributes as f, belongsTo as g, hasMany as h, createSnapshot as i, isElementDescriptor as j, lookupLegacySupport as l, normalizeModelName as n, rollbackAttributes as r, serialize as s, unloadRecord as u };