@ember-data/legacy-compat 5.6.0-beta.0 → 5.6.0-beta.1

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