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

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