@ember-data/legacy-compat 4.12.0-alpha.9 → 4.12.0-beta.4

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.
@@ -0,0 +1,1128 @@
1
+ import { macroCondition, getOwnConfig, importSync } from '@embroider/macros';
2
+ import { deprecate, assert, warn } from '@ember/debug';
3
+ import { SOURCE, coerceId } from '@ember-data/store/-private';
4
+ import { createDeferred } from '@ember-data/request';
5
+ /**
6
+ SnapshotRecordArray is not directly instantiable.
7
+ Instances are provided to consuming application's
8
+ adapters for certain requests.
9
+
10
+ @class SnapshotRecordArray
11
+ @public
12
+ */
13
+ class SnapshotRecordArray {
14
+ /**
15
+ SnapshotRecordArray is not directly instantiable.
16
+ Instances are provided to consuming application's
17
+ adapters and serializers for certain requests.
18
+ @method constructor
19
+ @private
20
+ @constructor
21
+ @param {Store} store
22
+ @param {string} type
23
+ @param options
24
+ */
25
+ constructor(store, type, options = {}) {
26
+ this.__store = store;
27
+ /**
28
+ An array of snapshots
29
+ @private
30
+ @property _snapshots
31
+ @type {Array}
32
+ */
33
+ this._snapshots = null;
34
+
35
+ /**
36
+ The modelName of the underlying records for the snapshots in the array, as a Model
37
+ @property modelName
38
+ @public
39
+ @type {Model}
40
+ */
41
+ this.modelName = type;
42
+
43
+ /**
44
+ A hash of adapter options passed into the store method for this request.
45
+ Example
46
+ ```app/adapters/post.js
47
+ import MyCustomAdapter from './custom-adapter';
48
+ export default class PostAdapter extends MyCustomAdapter {
49
+ findAll(store, type, sinceToken, snapshotRecordArray) {
50
+ if (snapshotRecordArray.adapterOptions.subscribe) {
51
+ // ...
52
+ }
53
+ // ...
54
+ }
55
+ }
56
+ ```
57
+ @property adapterOptions
58
+ @public
59
+ @type {Object}
60
+ */
61
+ this.adapterOptions = options.adapterOptions;
62
+
63
+ /**
64
+ The relationships to include for this request.
65
+ Example
66
+ ```app/adapters/application.js
67
+ import Adapter from '@ember-data/adapter';
68
+ export default class ApplicationAdapter extends Adapter {
69
+ findAll(store, type, snapshotRecordArray) {
70
+ let url = `/${type.modelName}?include=${encodeURIComponent(snapshotRecordArray.include)}`;
71
+ return fetch(url).then((response) => response.json())
72
+ }
73
+ }
74
+ ```
75
+ @property include
76
+ @public
77
+ @type {String|Array}
78
+ */
79
+ this.include = options.include;
80
+ }
81
+
82
+ /**
83
+ An array of records
84
+ @property _recordArray
85
+ @private
86
+ @type {Array}
87
+ */
88
+ get _recordArray() {
89
+ return this.__store.peekAll(this.modelName);
90
+ }
91
+
92
+ /**
93
+ Number of records in the array
94
+ Example
95
+ ```app/adapters/post.js
96
+ import JSONAPIAdapter from '@ember-data/adapter/json-api';
97
+ export default class PostAdapter extends JSONAPIAdapter {
98
+ shouldReloadAll(store, snapshotRecordArray) {
99
+ return !snapshotRecordArray.length;
100
+ }
101
+ });
102
+ ```
103
+ @property length
104
+ @public
105
+ @type {Number}
106
+ */
107
+ get length() {
108
+ return this._recordArray.length;
109
+ }
110
+
111
+ /**
112
+ Get snapshots of the underlying record array
113
+ Example
114
+ ```app/adapters/post.js
115
+ import JSONAPIAdapter from '@ember-data/adapter/json-api';
116
+ export default class PostAdapter extends JSONAPIAdapter {
117
+ shouldReloadAll(store, snapshotArray) {
118
+ let snapshots = snapshotArray.snapshots();
119
+ return snapshots.any(function(ticketSnapshot) {
120
+ let timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt'), 'minutes');
121
+ if (timeDiff > 20) {
122
+ return true;
123
+ } else {
124
+ return false;
125
+ }
126
+ });
127
+ }
128
+ }
129
+ ```
130
+ @method snapshots
131
+ @public
132
+ @return {Array} Array of snapshots
133
+ */
134
+ snapshots() {
135
+ if (this._snapshots !== null) {
136
+ return this._snapshots;
137
+ }
138
+ const {
139
+ _fetchManager
140
+ } = this.__store;
141
+ this._snapshots = this._recordArray[SOURCE].map(identifier => _fetchManager.createSnapshot(identifier));
142
+ return this._snapshots;
143
+ }
144
+ }
145
+ if (macroCondition(getOwnConfig().deprecations.DEPRECATE_SNAPSHOT_MODEL_CLASS_ACCESS)) {
146
+ /**
147
+ The type of the underlying records for the snapshots in the array, as a Model
148
+ @deprecated
149
+ @property type
150
+ @public
151
+ @type {Model}
152
+ */
153
+ Object.defineProperty(SnapshotRecordArray.prototype, 'type', {
154
+ get() {
155
+ deprecate(`Using SnapshotRecordArray.type to access the ModelClass for a record is deprecated. Use store.modelFor(<modelName>) instead.`, false, {
156
+ id: 'ember-data:deprecate-snapshot-model-class-access',
157
+ until: '5.0',
158
+ for: 'ember-data',
159
+ since: {
160
+ available: '4.5.0',
161
+ enabled: '4.5.0'
162
+ }
163
+ });
164
+ // @ts-expect-error
165
+ return this._recordArray.type;
166
+ }
167
+ });
168
+ }
169
+ function _bind(fn, ...args) {
170
+ return function () {
171
+ return fn.apply(undefined, args);
172
+ };
173
+ }
174
+ function _guard(promise, test) {
175
+ let guarded = promise.finally(() => {
176
+ if (!test()) {
177
+ guarded._subscribers ? guarded._subscribers.length = 0 : null;
178
+ }
179
+ });
180
+ return guarded;
181
+ }
182
+ function _objectIsAlive(object) {
183
+ return !(object.isDestroyed || object.isDestroying);
184
+ }
185
+ function guardDestroyedStore(promise, store) {
186
+ return promise.then(_v => {
187
+ if (!_objectIsAlive(store)) {
188
+ if (macroCondition(getOwnConfig().deprecations.DEPRECATE_RSVP_PROMISE)) {
189
+ deprecate(`A Promise did not resolve by the time the store was destroyed. This will error in a future release.`, false, {
190
+ id: 'ember-data:rsvp-unresolved-async',
191
+ until: '5.0',
192
+ for: '@ember-data/store',
193
+ since: {
194
+ available: '4.5',
195
+ enabled: '4.5'
196
+ }
197
+ });
198
+ }
199
+ }
200
+ return _v;
201
+ });
202
+ }
203
+ function assertIdentifierHasId(identifier) {
204
+ assert(`Attempted to schedule a fetch for a record without an id.`, identifier.id !== null);
205
+ }
206
+ function iterateData(data, fn) {
207
+ if (Array.isArray(data)) {
208
+ return data.map(fn);
209
+ } else {
210
+ return fn(data);
211
+ }
212
+ }
213
+ function payloadIsNotBlank(adapterPayload) {
214
+ if (Array.isArray(adapterPayload)) {
215
+ return true;
216
+ } else {
217
+ return Object.keys(adapterPayload || {}).length !== 0;
218
+ }
219
+ }
220
+
221
+ /**
222
+ This is a helper method that validates a JSON API top-level document
223
+
224
+ The format of a document is described here:
225
+ http://jsonapi.org/format/#document-top-level
226
+
227
+ @internal
228
+ */
229
+ function validateDocumentStructure(doc) {
230
+ if (macroCondition(getOwnConfig().env.DEBUG)) {
231
+ let errors = [];
232
+ if (!doc || typeof doc !== 'object') {
233
+ errors.push('Top level of a JSON API document must be an object');
234
+ } else {
235
+ if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) {
236
+ errors.push('One or more of the following keys must be present: "data", "errors", "meta".');
237
+ } else {
238
+ if ('data' in doc && 'errors' in doc) {
239
+ errors.push('Top level keys "errors" and "data" cannot both be present in a JSON API document');
240
+ }
241
+ }
242
+ if ('data' in doc) {
243
+ if (!(doc.data === null || Array.isArray(doc.data) || typeof doc.data === 'object')) {
244
+ errors.push('data must be null, an object, or an array');
245
+ }
246
+ }
247
+ if ('meta' in doc) {
248
+ if (typeof doc.meta !== 'object') {
249
+ errors.push('meta must be an object');
250
+ }
251
+ }
252
+ if ('errors' in doc) {
253
+ if (!Array.isArray(doc.errors)) {
254
+ errors.push('errors must be an array');
255
+ }
256
+ }
257
+ if ('links' in doc) {
258
+ if (typeof doc.links !== 'object') {
259
+ errors.push('links must be an object');
260
+ }
261
+ }
262
+ if ('jsonapi' in doc) {
263
+ if (typeof doc.jsonapi !== 'object') {
264
+ errors.push('jsonapi must be an object');
265
+ }
266
+ }
267
+ if ('included' in doc) {
268
+ if (typeof doc.included !== 'object') {
269
+ errors.push('included must be an array');
270
+ }
271
+ }
272
+ }
273
+ assert(`Response must be normalized to a valid JSON API document:\n\t* ${errors.join('\n\t* ')}`, errors.length === 0);
274
+ }
275
+ }
276
+ function normalizeResponseHelper(serializer, store, modelClass, payload, id, requestType) {
277
+ let normalizedResponse = serializer ? serializer.normalizeResponse(store, modelClass, payload, id, requestType) : payload;
278
+ validateDocumentStructure(normalizedResponse);
279
+ return normalizedResponse;
280
+ }
281
+
282
+ /**
283
+ @module @ember-data/store
284
+ */
285
+ /**
286
+ Snapshot is not directly instantiable.
287
+ Instances are provided to a consuming application's
288
+ adapters and serializers for certain requests.
289
+
290
+ Snapshots are only available when using `@ember-data/legacy-compat`
291
+ for legacy compatibility with adapters and serializers.
292
+
293
+ @class Snapshot
294
+ @public
295
+ */
296
+ class Snapshot {
297
+ /**
298
+ * @method constructor
299
+ * @constructor
300
+ * @private
301
+ * @param options
302
+ * @param identifier
303
+ * @param _store
304
+ */
305
+ constructor(options, identifier, store) {
306
+ this._store = store;
307
+ this.__attributes = null;
308
+ this._belongsToRelationships = Object.create(null);
309
+ this._belongsToIds = Object.create(null);
310
+ this._hasManyRelationships = Object.create(null);
311
+ this._hasManyIds = Object.create(null);
312
+ const hasRecord = !!store._instanceCache.peek({
313
+ identifier,
314
+ bucket: 'record'
315
+ });
316
+ this.modelName = identifier.type;
317
+
318
+ /**
319
+ The unique RecordIdentifier associated with this Snapshot.
320
+ @property identifier
321
+ @public
322
+ @type {StableRecordIdentifier}
323
+ */
324
+ this.identifier = identifier;
325
+
326
+ /*
327
+ If the we do not yet have a record, then we are
328
+ likely a snapshot being provided to a find request, so we
329
+ populate __attributes lazily. Else, to preserve the "moment
330
+ in time" in which a snapshot is created, we greedily grab
331
+ the values.
332
+ */
333
+ if (hasRecord) {
334
+ this._attributes;
335
+ }
336
+
337
+ /**
338
+ The id of the snapshot's underlying record
339
+ Example
340
+ ```javascript
341
+ // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
342
+ postSnapshot.id; // => '1'
343
+ ```
344
+ @property id
345
+ @type {String}
346
+ @public
347
+ */
348
+ this.id = identifier.id;
349
+
350
+ /**
351
+ A hash of adapter options
352
+ @property adapterOptions
353
+ @type {Object}
354
+ @public
355
+ */
356
+ this.adapterOptions = options.adapterOptions;
357
+
358
+ /**
359
+ If `include` was passed to the options hash for the request, the value
360
+ would be available here.
361
+ @property include
362
+ @type {String|Array}
363
+ @public
364
+ */
365
+ this.include = options.include;
366
+
367
+ /**
368
+ The name of the type of the underlying record for this snapshot, as a string.
369
+ @property modelName
370
+ @type {String}
371
+ @public
372
+ */
373
+ this.modelName = identifier.type;
374
+ if (hasRecord) {
375
+ const cache = macroCondition(getOwnConfig().deprecations.DEPRECATE_V1_RECORD_DATA) ? this._store._instanceCache.getResourceCache(identifier) : this._store.cache;
376
+ this._changedAttributes = cache.changedAttrs(identifier);
377
+ }
378
+ }
379
+
380
+ /**
381
+ The underlying record for this snapshot. Can be used to access methods and
382
+ properties defined on the record.
383
+ Example
384
+ ```javascript
385
+ let json = snapshot.record.toJSON();
386
+ ```
387
+ @property record
388
+ @type {Model}
389
+ @public
390
+ */
391
+ get record() {
392
+ return this._store._instanceCache.getRecord(this.identifier);
393
+ }
394
+ get _attributes() {
395
+ if (this.__attributes !== null) {
396
+ return this.__attributes;
397
+ }
398
+ const attributes = this.__attributes = Object.create(null);
399
+ const {
400
+ identifier
401
+ } = this;
402
+ const attrs = Object.keys(this._store.getSchemaDefinitionService().attributesDefinitionFor(identifier));
403
+ const cache = macroCondition(getOwnConfig().deprecations.DEPRECATE_V1_RECORD_DATA) ? this._store._instanceCache.getResourceCache(identifier) : this._store.cache;
404
+ attrs.forEach(keyName => {
405
+ attributes[keyName] = cache.getAttr(identifier, keyName);
406
+ });
407
+ return attributes;
408
+ }
409
+
410
+ /**
411
+ The type of the underlying record for this snapshot, as a Model.
412
+ @property type
413
+ @public
414
+ @deprecated
415
+ @type {Model}
416
+ */
417
+
418
+ get isNew() {
419
+ const cache = macroCondition(getOwnConfig().deprecations.DEPRECATE_V1_RECORD_DATA) ? this._store._instanceCache.peek({
420
+ identifier: this.identifier,
421
+ bucket: 'resourceCache'
422
+ }) : this._store.cache;
423
+ return cache?.isNew(this.identifier) || false;
424
+ }
425
+
426
+ /**
427
+ Returns the value of an attribute.
428
+ Example
429
+ ```javascript
430
+ // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
431
+ postSnapshot.attr('author'); // => 'Tomster'
432
+ postSnapshot.attr('title'); // => 'Ember.js rocks'
433
+ ```
434
+ Note: Values are loaded eagerly and cached when the snapshot is created.
435
+ @method attr
436
+ @param {String} keyName
437
+ @return {Object} The attribute value or undefined
438
+ @public
439
+ */
440
+ attr(keyName) {
441
+ if (keyName in this._attributes) {
442
+ return this._attributes[keyName];
443
+ }
444
+ assert(`Model '${this.identifier.lid}' has no attribute named '${keyName}' defined.`, false);
445
+ }
446
+
447
+ /**
448
+ Returns all attributes and their corresponding values.
449
+ Example
450
+ ```javascript
451
+ // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
452
+ postSnapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' }
453
+ ```
454
+ @method attributes
455
+ @return {Object} All attributes of the current snapshot
456
+ @public
457
+ */
458
+ attributes() {
459
+ return {
460
+ ...this._attributes
461
+ };
462
+ }
463
+
464
+ /**
465
+ Returns all changed attributes and their old and new values.
466
+ Example
467
+ ```javascript
468
+ // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' });
469
+ postModel.set('title', 'Ember.js rocks!');
470
+ postSnapshot.changedAttributes(); // => { title: ['Ember.js rocks', 'Ember.js rocks!'] }
471
+ ```
472
+ @method changedAttributes
473
+ @return {Object} All changed attributes of the current snapshot
474
+ @public
475
+ */
476
+ changedAttributes() {
477
+ let changedAttributes = Object.create(null);
478
+ if (!this._changedAttributes) {
479
+ return changedAttributes;
480
+ }
481
+ let changedAttributeKeys = Object.keys(this._changedAttributes);
482
+ for (let i = 0, length = changedAttributeKeys.length; i < length; i++) {
483
+ let key = changedAttributeKeys[i];
484
+ changedAttributes[key] = this._changedAttributes[key].slice();
485
+ }
486
+ return changedAttributes;
487
+ }
488
+
489
+ /**
490
+ Returns the current value of a belongsTo relationship.
491
+ `belongsTo` takes an optional hash of options as a second parameter,
492
+ currently supported options are:
493
+ - `id`: set to `true` if you only want the ID of the related record to be
494
+ returned.
495
+ Example
496
+ ```javascript
497
+ // store.push('post', { id: 1, title: 'Hello World' });
498
+ // store.createRecord('comment', { body: 'Lorem ipsum', post: post });
499
+ commentSnapshot.belongsTo('post'); // => Snapshot
500
+ commentSnapshot.belongsTo('post', { id: true }); // => '1'
501
+ // store.push('comment', { id: 1, body: 'Lorem ipsum' });
502
+ commentSnapshot.belongsTo('post'); // => undefined
503
+ ```
504
+ Calling `belongsTo` will return a new Snapshot as long as there's any known
505
+ data for the relationship available, such as an ID. If the relationship is
506
+ known but unset, `belongsTo` will return `null`. If the contents of the
507
+ relationship is unknown `belongsTo` will return `undefined`.
508
+ Note: Relationships are loaded lazily and cached upon first access.
509
+ @method belongsTo
510
+ @param {String} keyName
511
+ @param {Object} [options]
512
+ @public
513
+ @return {(Snapshot|String|null|undefined)} A snapshot or ID of a known
514
+ relationship or null if the relationship is known but unset. undefined
515
+ will be returned if the contents of the relationship is unknown.
516
+ */
517
+ belongsTo(keyName, options) {
518
+ let returnModeIsId = !!(options && options.id);
519
+ let result;
520
+ let store = this._store;
521
+ if (returnModeIsId === true && keyName in this._belongsToIds) {
522
+ return this._belongsToIds[keyName];
523
+ }
524
+ if (returnModeIsId === false && keyName in this._belongsToRelationships) {
525
+ return this._belongsToRelationships[keyName];
526
+ }
527
+ let relationshipMeta = store.getSchemaDefinitionService().relationshipsDefinitionFor({
528
+ type: this.modelName
529
+ })[keyName];
530
+ assert(`Model '${this.identifier.lid}' has no belongsTo relationship named '${keyName}' defined.`, relationshipMeta && relationshipMeta.kind === 'belongsTo');
531
+
532
+ // TODO @runspired it seems this code branch would not work with CUSTOM_MODEL_CLASSes
533
+ // this check is not a regression in behavior because relationships don't currently
534
+ // function without access to intimate API contracts between RecordData and Model.
535
+ // This is a requirement we should fix as soon as the relationship layer does not require
536
+ // this intimate API usage.
537
+ if (macroCondition(!getOwnConfig().packages.HAS_JSON_API_PACKAGE)) {
538
+ assert(`snapshot.belongsTo only supported when using the package @ember-data/json-api`);
539
+ }
540
+ const graphFor = importSync('@ember-data/graph/-private').graphFor;
541
+ const {
542
+ identifier
543
+ } = this;
544
+ const relationship = graphFor(this._store).get(identifier, keyName);
545
+ assert(`You looked up the ${keyName} belongsTo relationship for { type: ${identifier.type}, id: ${identifier.id || ''}, lid: ${identifier.lid} but no such relationship was found.`, relationship);
546
+ assert(`You looked up the ${keyName} belongsTo relationship for { type: ${identifier.type}, id: ${identifier.id || ''}, lid: ${identifier.lid} but that relationship is a hasMany.`, relationship.definition.kind === 'belongsTo');
547
+ let value = relationship.getData();
548
+ let data = value && value.data;
549
+ let inverseIdentifier = data ? store.identifierCache.getOrCreateRecordIdentifier(data) : null;
550
+ if (value && value.data !== undefined) {
551
+ const cache = macroCondition(getOwnConfig().deprecations.DEPRECATE_V1_RECORD_DATA) ? inverseIdentifier && store._instanceCache.getResourceCache(inverseIdentifier) : store.cache;
552
+ if (inverseIdentifier && !cache.isDeleted(inverseIdentifier)) {
553
+ if (returnModeIsId) {
554
+ result = inverseIdentifier.id;
555
+ } else {
556
+ result = store._fetchManager.createSnapshot(inverseIdentifier);
557
+ }
558
+ } else {
559
+ result = null;
560
+ }
561
+ }
562
+ if (returnModeIsId) {
563
+ this._belongsToIds[keyName] = result;
564
+ } else {
565
+ this._belongsToRelationships[keyName] = result;
566
+ }
567
+ return result;
568
+ }
569
+
570
+ /**
571
+ Returns the current value of a hasMany relationship.
572
+ `hasMany` takes an optional hash of options as a second parameter,
573
+ currently supported options are:
574
+ - `ids`: set to `true` if you only want the IDs of the related records to be
575
+ returned.
576
+ Example
577
+ ```javascript
578
+ // store.push('post', { id: 1, title: 'Hello World', comments: [2, 3] });
579
+ postSnapshot.hasMany('comments'); // => [Snapshot, Snapshot]
580
+ postSnapshot.hasMany('comments', { ids: true }); // => ['2', '3']
581
+ // store.push('post', { id: 1, title: 'Hello World' });
582
+ postSnapshot.hasMany('comments'); // => undefined
583
+ ```
584
+ Note: Relationships are loaded lazily and cached upon first access.
585
+ @method hasMany
586
+ @param {String} keyName
587
+ @param {Object} [options]
588
+ @public
589
+ @return {(Array|undefined)} An array of snapshots or IDs of a known
590
+ relationship or an empty array if the relationship is known but unset.
591
+ undefined will be returned if the contents of the relationship is unknown.
592
+ */
593
+ hasMany(keyName, options) {
594
+ let returnModeIsIds = !!(options && options.ids);
595
+ let results;
596
+ let cachedIds = this._hasManyIds[keyName];
597
+ let cachedSnapshots = this._hasManyRelationships[keyName];
598
+ if (returnModeIsIds === true && keyName in this._hasManyIds) {
599
+ return cachedIds;
600
+ }
601
+ if (returnModeIsIds === false && keyName in this._hasManyRelationships) {
602
+ return cachedSnapshots;
603
+ }
604
+ let store = this._store;
605
+ let relationshipMeta = store.getSchemaDefinitionService().relationshipsDefinitionFor({
606
+ type: this.modelName
607
+ })[keyName];
608
+ assert(`Model '${this.identifier.lid}' has no hasMany relationship named '${keyName}' defined.`, relationshipMeta && relationshipMeta.kind === 'hasMany');
609
+
610
+ // TODO @runspired it seems this code branch would not work with CUSTOM_MODEL_CLASSes
611
+ // this check is not a regression in behavior because relationships don't currently
612
+ // function without access to intimate API contracts between RecordData and Model.
613
+ // This is a requirement we should fix as soon as the relationship layer does not require
614
+ // this intimate API usage.
615
+ if (macroCondition(!getOwnConfig().packages.HAS_JSON_API_PACKAGE)) {
616
+ assert(`snapshot.hasMany only supported when using the package @ember-data/json-api`);
617
+ }
618
+ const graphFor = importSync('@ember-data/graph/-private').graphFor;
619
+ const {
620
+ identifier
621
+ } = this;
622
+ const relationship = graphFor(this._store).get(identifier, keyName);
623
+ assert(`You looked up the ${keyName} hasMany relationship for { type: ${identifier.type}, id: ${identifier.id || ''}, lid: ${identifier.lid} but no such relationship was found.`, relationship);
624
+ assert(`You looked up the ${keyName} hasMany relationship for { type: ${identifier.type}, id: ${identifier.id || ''}, lid: ${identifier.lid} but that relationship is a belongsTo.`, relationship.definition.kind === 'hasMany');
625
+ let value = relationship.getData();
626
+ if (value.data) {
627
+ results = [];
628
+ value.data.forEach(member => {
629
+ let inverseIdentifier = store.identifierCache.getOrCreateRecordIdentifier(member);
630
+ const cache = macroCondition(getOwnConfig().deprecations.DEPRECATE_V1_RECORD_DATA) ? store._instanceCache.getResourceCache(inverseIdentifier) : store.cache;
631
+ if (!cache.isDeleted(inverseIdentifier)) {
632
+ if (returnModeIsIds) {
633
+ results.push(inverseIdentifier.id);
634
+ } else {
635
+ results.push(store._fetchManager.createSnapshot(inverseIdentifier));
636
+ }
637
+ }
638
+ });
639
+ }
640
+
641
+ // we assign even if `undefined` so that we don't reprocess the relationship
642
+ // on next access. This works with the `keyName in` checks above.
643
+ if (returnModeIsIds) {
644
+ this._hasManyIds[keyName] = results;
645
+ } else {
646
+ this._hasManyRelationships[keyName] = results;
647
+ }
648
+ return results;
649
+ }
650
+
651
+ /**
652
+ Iterates through all the attributes of the model, calling the passed
653
+ function on each attribute.
654
+ Example
655
+ ```javascript
656
+ snapshot.eachAttribute(function(name, meta) {
657
+ // ...
658
+ });
659
+ ```
660
+ @method eachAttribute
661
+ @param {Function} callback the callback to execute
662
+ @param {Object} [binding] the value to which the callback's `this` should be bound
663
+ @public
664
+ */
665
+ eachAttribute(callback, binding) {
666
+ let attrDefs = this._store.getSchemaDefinitionService().attributesDefinitionFor(this.identifier);
667
+ Object.keys(attrDefs).forEach(key => {
668
+ callback.call(binding, key, attrDefs[key]);
669
+ });
670
+ }
671
+
672
+ /**
673
+ Iterates through all the relationships of the model, calling the passed
674
+ function on each relationship.
675
+ Example
676
+ ```javascript
677
+ snapshot.eachRelationship(function(name, relationship) {
678
+ // ...
679
+ });
680
+ ```
681
+ @method eachRelationship
682
+ @param {Function} callback the callback to execute
683
+ @param {Object} [binding] the value to which the callback's `this` should be bound
684
+ @public
685
+ */
686
+ eachRelationship(callback, binding) {
687
+ let relationshipDefs = this._store.getSchemaDefinitionService().relationshipsDefinitionFor(this.identifier);
688
+ Object.keys(relationshipDefs).forEach(key => {
689
+ callback.call(binding, key, relationshipDefs[key]);
690
+ });
691
+ }
692
+
693
+ /**
694
+ Serializes the snapshot using the serializer for the model.
695
+ Example
696
+ ```app/adapters/application.js
697
+ import Adapter from '@ember-data/adapter';
698
+ export default Adapter.extend({
699
+ createRecord(store, type, snapshot) {
700
+ let data = snapshot.serialize({ includeId: true });
701
+ let url = `/${type.modelName}`;
702
+ return fetch(url, {
703
+ method: 'POST',
704
+ body: data,
705
+ }).then((response) => response.json())
706
+ }
707
+ });
708
+ ```
709
+ @method serialize
710
+ @param {Object} options
711
+ @return {Object} an object whose values are primitive JSON values only
712
+ @public
713
+ */
714
+ serialize(options) {
715
+ const serializer = this._store.serializerFor(this.modelName);
716
+ assert(`Cannot serialize record, no serializer found`, serializer);
717
+ return serializer.serialize(this, options);
718
+ }
719
+ }
720
+ if (macroCondition(getOwnConfig().deprecations.DEPRECATE_SNAPSHOT_MODEL_CLASS_ACCESS)) {
721
+ Object.defineProperty(Snapshot.prototype, 'type', {
722
+ get() {
723
+ deprecate(`Using Snapshot.type to access the ModelClass for a record is deprecated. Use store.modelFor(<modelName>) instead.`, false, {
724
+ id: 'ember-data:deprecate-snapshot-model-class-access',
725
+ until: '5.0',
726
+ for: 'ember-data',
727
+ since: {
728
+ available: '4.5.0',
729
+ enabled: '4.5.0'
730
+ }
731
+ });
732
+ return this._store.modelFor(this.identifier.type);
733
+ }
734
+ });
735
+ }
736
+ const SaveOp = Symbol('SaveOp');
737
+ class FetchManager {
738
+ // fetches pending in the runloop, waiting to be coalesced
739
+
740
+ constructor(store) {
741
+ this._store = store;
742
+ // used to keep track of all the find requests that need to be coalesced
743
+ this._pendingFetch = new Map();
744
+ this.requestCache = store.getRequestStateService();
745
+ this.isDestroyed = false;
746
+ }
747
+ createSnapshot(identifier, options = {}) {
748
+ return new Snapshot(options, identifier, this._store);
749
+ }
750
+
751
+ /**
752
+ This method is called by `record.save`, and gets passed a
753
+ resolver for the promise that `record.save` returns.
754
+ It schedules saving to happen at the end of the run loop.
755
+ @internal
756
+ */
757
+ scheduleSave(identifier, options) {
758
+ let resolver = createDeferred();
759
+ let query = {
760
+ op: 'saveRecord',
761
+ recordIdentifier: identifier,
762
+ options
763
+ };
764
+ let queryRequest = {
765
+ data: [query]
766
+ };
767
+ const snapshot = this.createSnapshot(identifier, options);
768
+ const pendingSaveItem = {
769
+ snapshot: snapshot,
770
+ resolver: resolver,
771
+ identifier,
772
+ options,
773
+ queryRequest
774
+ };
775
+ const monitored = this.requestCache.enqueue(resolver.promise, pendingSaveItem.queryRequest);
776
+ _flushPendingSave(this._store, pendingSaveItem);
777
+ return monitored;
778
+ }
779
+ scheduleFetch(identifier, options, request) {
780
+ let query = {
781
+ op: 'findRecord',
782
+ recordIdentifier: identifier,
783
+ options
784
+ };
785
+ let queryRequest = {
786
+ data: [query]
787
+ };
788
+ let pendingFetch = this.getPendingFetch(identifier, options);
789
+ if (pendingFetch) {
790
+ return pendingFetch;
791
+ }
792
+ let modelName = identifier.type;
793
+ const resolver = createDeferred();
794
+ const pendingFetchItem = {
795
+ identifier,
796
+ resolver,
797
+ options,
798
+ queryRequest
799
+ };
800
+ let resolverPromise = resolver.promise;
801
+ const store = this._store;
802
+ const isInitialLoad = !store._instanceCache.recordIsLoaded(identifier); // we don't use isLoading directly because we are the request
803
+
804
+ const monitored = this.requestCache.enqueue(resolverPromise, pendingFetchItem.queryRequest);
805
+ let promise = monitored.then(payload => {
806
+ // ensure that regardless of id returned we assign to the correct record
807
+ if (payload.data && !Array.isArray(payload.data)) {
808
+ payload.data.lid = identifier.lid;
809
+ }
810
+
811
+ // additional data received in the payload
812
+ // may result in the merging of identifiers (and thus records)
813
+ let potentiallyNewIm = store._push(payload, options.reload);
814
+ if (potentiallyNewIm && !Array.isArray(potentiallyNewIm)) {
815
+ return potentiallyNewIm;
816
+ }
817
+ return identifier;
818
+ }, error => {
819
+ assert(`Async Leak Detected: Expected the store to not be destroyed`, !store.isDestroyed);
820
+ const cache = macroCondition(getOwnConfig().deprecations.DEPRECATE_V1_RECORD_DATA) ? store._instanceCache.peek({
821
+ identifier,
822
+ bucket: 'resourceCache'
823
+ }) : store.cache;
824
+ if (!cache || cache.isEmpty(identifier) || isInitialLoad) {
825
+ let isReleasable = true;
826
+ if (macroCondition(getOwnConfig().packages.HAS_GRAPH_PACKAGE)) {
827
+ if (!cache) {
828
+ const graphFor = importSync('@ember-data/graph/-private').graphFor;
829
+ const graph = graphFor(store);
830
+ isReleasable = graph.isReleasable(identifier);
831
+ if (!isReleasable) {
832
+ graph.unload(identifier, true);
833
+ }
834
+ }
835
+ }
836
+ if (cache || isReleasable) {
837
+ store._enableAsyncFlush = true;
838
+ store._instanceCache.unloadRecord(identifier);
839
+ store._enableAsyncFlush = null;
840
+ }
841
+ }
842
+ throw error;
843
+ });
844
+ if (this._pendingFetch.size === 0) {
845
+ void new Promise(resolve => setTimeout(resolve, 0)).then(() => {
846
+ this.flushAllPendingFetches();
847
+ });
848
+ }
849
+ let fetches = this._pendingFetch;
850
+ if (!fetches.has(modelName)) {
851
+ fetches.set(modelName, []);
852
+ }
853
+ fetches.get(modelName).push(pendingFetchItem);
854
+ if (macroCondition(getOwnConfig().env.TESTING)) {
855
+ if (!request.disableTestWaiter) {
856
+ const {
857
+ waitForPromise
858
+ } = importSync('@ember/test-waiters');
859
+ promise = waitForPromise(promise);
860
+ }
861
+ }
862
+ pendingFetchItem.promise = promise;
863
+ return promise;
864
+ }
865
+ getPendingFetch(identifier, options) {
866
+ let pendingFetches = this._pendingFetch.get(identifier.type);
867
+
868
+ // We already have a pending fetch for this
869
+ if (pendingFetches) {
870
+ let matchingPendingFetch = pendingFetches.find(fetch => fetch.identifier === identifier && isSameRequest(options, fetch.options));
871
+ if (matchingPendingFetch) {
872
+ return matchingPendingFetch.promise;
873
+ }
874
+ }
875
+ }
876
+ flushAllPendingFetches() {
877
+ if (this.isDestroyed) {
878
+ return;
879
+ }
880
+ const store = this._store;
881
+ this._pendingFetch.forEach((fetchItem, type) => _flushPendingFetchForType(store, fetchItem, type));
882
+ this._pendingFetch.clear();
883
+ }
884
+ fetchDataIfNeededForIdentifier(identifier, options = {}, request) {
885
+ // pre-loading will change the isEmpty value
886
+ const isEmpty = _isEmpty(this._store._instanceCache, identifier);
887
+ const isLoading = _isLoading(this._store._instanceCache, identifier);
888
+ let promise;
889
+ if (isEmpty) {
890
+ assertIdentifierHasId(identifier);
891
+ if (macroCondition(getOwnConfig().env.DEBUG)) {
892
+ promise = this.scheduleFetch(identifier, Object.assign({}, options, {
893
+ reload: true
894
+ }), request);
895
+ } else {
896
+ options.reload = true;
897
+ promise = this.scheduleFetch(identifier, options, request);
898
+ }
899
+ } else if (isLoading) {
900
+ promise = this.getPendingFetch(identifier, options);
901
+ assert(`Expected to find a pending request for a record in the loading state, but found none`, promise);
902
+ } else {
903
+ promise = Promise.resolve(identifier);
904
+ }
905
+ return promise;
906
+ }
907
+ destroy() {
908
+ this.isDestroyed = true;
909
+ }
910
+ }
911
+ function _isEmpty(instanceCache, identifier) {
912
+ const cache = macroCondition(getOwnConfig().deprecations.DEPRECATE_V1_RECORD_DATA) ? instanceCache.__instances.resourceCache.get(identifier) : instanceCache.cache;
913
+ if (!cache) {
914
+ return true;
915
+ }
916
+ const isNew = cache.isNew(identifier);
917
+ const isDeleted = cache.isDeleted(identifier);
918
+ const isEmpty = cache.isEmpty(identifier);
919
+ return (!isNew || isDeleted) && isEmpty;
920
+ }
921
+ function _isLoading(cache, identifier) {
922
+ const req = cache.store.getRequestStateService();
923
+ // const fulfilled = req.getLastRequestForRecord(identifier);
924
+ const isLoaded = cache.recordIsLoaded(identifier);
925
+ return !isLoaded &&
926
+ // fulfilled === null &&
927
+ req.getPendingRequestsForRecord(identifier).some(req => req.type === 'query');
928
+ }
929
+
930
+ // this function helps resolve whether we have a pending request that we should use instead
931
+ function isSameRequest(options = {}, existingOptions = {}) {
932
+ let includedMatches = !options.include || options.include === existingOptions.include;
933
+ let adapterOptionsMatches = options.adapterOptions === existingOptions.adapterOptions;
934
+ return includedMatches && adapterOptionsMatches;
935
+ }
936
+ function _findMany(store, adapter, modelName, snapshots) {
937
+ let modelClass = store.modelFor(modelName); // `adapter.findMany` gets the modelClass still
938
+ let promise = Promise.resolve().then(() => {
939
+ const ids = snapshots.map(s => s.id);
940
+ assert(`Cannot fetch a record without an id`, ids.every(v => v !== null));
941
+ // eslint-disable-next-line @typescript-eslint/unbound-method
942
+ assert(`Expected this adapter to implement findMany for coalescing`, adapter.findMany);
943
+ let ret = adapter.findMany(store, modelClass, ids, snapshots);
944
+ assert('adapter.findMany returned undefined, this was very likely a mistake', ret !== undefined);
945
+ return ret;
946
+ });
947
+ promise = guardDestroyedStore(promise, store);
948
+ return promise.then(adapterPayload => {
949
+ assert(`You made a 'findMany' request for '${modelName}' records with ids '[${snapshots.map(s => s.id).join(',')}]', but the adapter's response did not have any data`, !!payloadIsNotBlank(adapterPayload));
950
+ let serializer = store.serializerFor(modelName);
951
+ let payload = normalizeResponseHelper(serializer, store, modelClass, adapterPayload, null, 'findMany');
952
+ return payload;
953
+ });
954
+ }
955
+ function rejectFetchedItems(fetchMap, snapshots, error) {
956
+ for (let i = 0, l = snapshots.length; i < l; i++) {
957
+ let snapshot = snapshots[i];
958
+ let pair = fetchMap.get(snapshot);
959
+ if (pair) {
960
+ pair.resolver.reject(error || new Error(`Expected: '<${snapshot.modelName}:${snapshot.id}>' to be present in the adapter provided payload, but it was not found.`));
961
+ }
962
+ }
963
+ }
964
+ function handleFoundRecords(store, fetchMap, snapshots, coalescedPayload) {
965
+ /*
966
+ It is possible that the same ID is included multiple times
967
+ via multiple snapshots. This happens when more than one
968
+ options hash was supplied, each of which must be uniquely
969
+ accounted for.
970
+ However, since we can't map from response to a specific
971
+ options object, we resolve all snapshots by id with
972
+ the first response we see.
973
+ */
974
+ let snapshotsById = new Map();
975
+ for (let i = 0; i < snapshots.length; i++) {
976
+ let id = snapshots[i].id;
977
+ let snapshotGroup = snapshotsById.get(id);
978
+ if (!snapshotGroup) {
979
+ snapshotGroup = [];
980
+ snapshotsById.set(id, snapshotGroup);
981
+ }
982
+ snapshotGroup.push(snapshots[i]);
983
+ }
984
+ const included = Array.isArray(coalescedPayload.included) ? coalescedPayload.included : [];
985
+
986
+ // resolve found records
987
+ let resources = coalescedPayload.data;
988
+ for (let i = 0, l = resources.length; i < l; i++) {
989
+ let resource = resources[i];
990
+ let snapshotGroup = snapshotsById.get(resource.id);
991
+ snapshotsById.delete(resource.id);
992
+ if (!snapshotGroup) {
993
+ // TODO consider whether this should be a deprecation/assertion
994
+ included.push(resource);
995
+ } else {
996
+ snapshotGroup.forEach(snapshot => {
997
+ let pair = fetchMap.get(snapshot);
998
+ let resolver = pair.resolver;
999
+ resolver.resolve({
1000
+ data: resource
1001
+ });
1002
+ });
1003
+ }
1004
+ }
1005
+ if (included.length > 0) {
1006
+ store._push({
1007
+ data: null,
1008
+ included
1009
+ }, true);
1010
+ }
1011
+ if (snapshotsById.size === 0) {
1012
+ return;
1013
+ }
1014
+
1015
+ // reject missing records
1016
+ let rejected = [];
1017
+ snapshotsById.forEach(snapshots => {
1018
+ rejected.push(...snapshots);
1019
+ });
1020
+ warn('Ember Data expected to find records with the following ids in the adapter response from findMany but they were missing: [ "' + [...snapshotsById.values()].map(r => r[0].id).join('", "') + '" ]', {
1021
+ id: 'ds.store.missing-records-from-adapter'
1022
+ });
1023
+ rejectFetchedItems(fetchMap, rejected);
1024
+ }
1025
+ function _fetchRecord(store, adapter, fetchItem) {
1026
+ let identifier = fetchItem.identifier;
1027
+ let modelName = identifier.type;
1028
+ assert(`You tried to find a record but you have no adapter (for ${modelName})`, adapter);
1029
+ assert(`You tried to find a record but your adapter (for ${modelName}) does not implement 'findRecord'`, typeof adapter.findRecord === 'function');
1030
+ let snapshot = store._fetchManager.createSnapshot(identifier, fetchItem.options);
1031
+ let klass = store.modelFor(identifier.type);
1032
+ let id = identifier.id;
1033
+ let promise = Promise.resolve().then(() => {
1034
+ return adapter.findRecord(store, klass, identifier.id, snapshot);
1035
+ });
1036
+ promise = promise.then(adapterPayload => {
1037
+ assert(`Async Leak Detected: Expected the store to not be destroyed`, _objectIsAlive(store));
1038
+ assert(`You made a 'findRecord' request for a '${modelName}' with id '${id}', but the adapter's response did not have any data`, !!payloadIsNotBlank(adapterPayload));
1039
+ let serializer = store.serializerFor(modelName);
1040
+ let payload = normalizeResponseHelper(serializer, store, klass, adapterPayload, id, 'findRecord');
1041
+ assert(`Ember Data expected the primary data returned from a 'findRecord' response to be an object but instead it found an array.`, !Array.isArray(payload.data));
1042
+ assert(`The 'findRecord' request for ${modelName}:${id} resolved indicating success but contained no primary data. To indicate a 404 not found you should either reject the promise returned by the adapter's findRecord method or throw a NotFoundError.`, 'data' in payload && payload.data !== null && typeof payload.data === 'object');
1043
+ warn(`You requested a record of type '${modelName}' with id '${id}' but the adapter returned a payload with primary data having an id of '${payload.data.id}'. Use 'store.findRecord()' when the requested id is the same as the one returned by the adapter. In other cases use 'store.queryRecord()' instead.`, coerceId(payload.data.id) === coerceId(id), {
1044
+ id: 'ds.store.findRecord.id-mismatch'
1045
+ });
1046
+ return payload;
1047
+ });
1048
+ fetchItem.resolver.resolve(promise);
1049
+ }
1050
+ function _processCoalescedGroup(store, fetchMap, group, adapter, modelName) {
1051
+ if (group.length > 1) {
1052
+ _findMany(store, adapter, modelName, group).then(payloads => {
1053
+ handleFoundRecords(store, fetchMap, group, payloads);
1054
+ }).catch(error => {
1055
+ rejectFetchedItems(fetchMap, group, error);
1056
+ });
1057
+ } else if (group.length === 1) {
1058
+ _fetchRecord(store, adapter, fetchMap.get(group[0]));
1059
+ } else {
1060
+ assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false);
1061
+ }
1062
+ }
1063
+ function _flushPendingFetchForType(store, pendingFetchItems, modelName) {
1064
+ let adapter = store.adapterFor(modelName);
1065
+ let shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests;
1066
+ let totalItems = pendingFetchItems.length;
1067
+ if (shouldCoalesce) {
1068
+ let snapshots = new Array(totalItems);
1069
+ let fetchMap = new Map();
1070
+ for (let i = 0; i < totalItems; i++) {
1071
+ let fetchItem = pendingFetchItems[i];
1072
+ snapshots[i] = store._fetchManager.createSnapshot(fetchItem.identifier, fetchItem.options);
1073
+ fetchMap.set(snapshots[i], fetchItem);
1074
+ }
1075
+ let groups;
1076
+ if (adapter.groupRecordsForFindMany) {
1077
+ groups = adapter.groupRecordsForFindMany(store, snapshots);
1078
+ } else {
1079
+ groups = [snapshots];
1080
+ }
1081
+ for (let i = 0, l = groups.length; i < l; i++) {
1082
+ _processCoalescedGroup(store, fetchMap, groups[i], adapter, modelName);
1083
+ }
1084
+ } else {
1085
+ for (let i = 0; i < totalItems; i++) {
1086
+ void _fetchRecord(store, adapter, pendingFetchItems[i]);
1087
+ }
1088
+ }
1089
+ }
1090
+ function _flushPendingSave(store, pending) {
1091
+ const {
1092
+ snapshot,
1093
+ resolver,
1094
+ identifier,
1095
+ options
1096
+ } = pending;
1097
+ const adapter = store.adapterFor(identifier.type);
1098
+ const operation = options[SaveOp];
1099
+ let modelName = snapshot.modelName;
1100
+ let modelClass = store.modelFor(modelName);
1101
+ const record = store._instanceCache.getRecord(identifier);
1102
+ assert(`You tried to update a record but you have no adapter (for ${modelName})`, adapter);
1103
+ assert(`You tried to update a record but your adapter (for ${modelName}) does not implement '${operation}'`, typeof adapter[operation] === 'function');
1104
+ let promise = Promise.resolve().then(() => adapter[operation](store, modelClass, snapshot));
1105
+ let serializer = store.serializerFor(modelName);
1106
+ assert(`Your adapter's '${operation}' method must return a value, but it returned 'undefined'`, promise !== undefined);
1107
+ promise = promise.then(adapterPayload => {
1108
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call
1109
+ if (!_objectIsAlive(record)) {
1110
+ if (macroCondition(getOwnConfig().deprecations.DEPRECATE_RSVP_PROMISE)) {
1111
+ deprecate(`A Promise while saving ${modelName} did not resolve by the time your model was destroyed. This will error in a future release.`, false, {
1112
+ id: 'ember-data:rsvp-unresolved-async',
1113
+ until: '5.0',
1114
+ for: '@ember-data/store',
1115
+ since: {
1116
+ available: '4.5',
1117
+ enabled: '4.5'
1118
+ }
1119
+ });
1120
+ }
1121
+ }
1122
+ if (adapterPayload) {
1123
+ return normalizeResponseHelper(serializer, store, modelClass, adapterPayload, snapshot.id, operation);
1124
+ }
1125
+ });
1126
+ resolver.resolve(promise);
1127
+ }
1128
+ export { FetchManager as F, SnapshotRecordArray as S, _objectIsAlive as _, SaveOp as a, Snapshot as b, _guard as c, _bind as d, assertIdentifierHasId as e, guardDestroyedStore as g, iterateData as i, normalizeResponseHelper as n, payloadIsNotBlank as p };