@ember-data/legacy-compat 4.12.7 → 4.13.0-alpha.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 (60) hide show
  1. package/README.md +8 -0
  2. package/addon-main.cjs +5 -0
  3. package/{addon/fetch-manager-025964e9.js → dist/-private-BJlhRRce.js} +321 -194
  4. package/dist/-private-BJlhRRce.js.map +1 -0
  5. package/dist/-private.js +1 -0
  6. package/dist/builders.js +303 -0
  7. package/dist/builders.js.map +1 -0
  8. package/dist/index.js +1087 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/utils-XGHLsgBS.js +23 -0
  11. package/dist/utils-XGHLsgBS.js.map +1 -0
  12. package/dist/utils.js +246 -0
  13. package/dist/utils.js.map +1 -0
  14. package/package.json +72 -35
  15. package/unstable-preview-types/-private.d.ts +17 -0
  16. package/unstable-preview-types/-private.d.ts.map +1 -0
  17. package/unstable-preview-types/builders/find-all.d.ts +41 -0
  18. package/unstable-preview-types/builders/find-all.d.ts.map +1 -0
  19. package/unstable-preview-types/builders/find-record.d.ts +62 -0
  20. package/unstable-preview-types/builders/find-record.d.ts.map +1 -0
  21. package/unstable-preview-types/builders/query.d.ts +72 -0
  22. package/unstable-preview-types/builders/query.d.ts.map +1 -0
  23. package/unstable-preview-types/builders/save-record.d.ts +40 -0
  24. package/unstable-preview-types/builders/save-record.d.ts.map +1 -0
  25. package/unstable-preview-types/builders/utils.d.ts +6 -0
  26. package/unstable-preview-types/builders/utils.d.ts.map +1 -0
  27. package/unstable-preview-types/builders.d.ts +18 -0
  28. package/unstable-preview-types/builders.d.ts.map +1 -0
  29. package/unstable-preview-types/index.d.ts +163 -0
  30. package/unstable-preview-types/index.d.ts.map +1 -0
  31. package/unstable-preview-types/legacy-network-handler/fetch-manager.d.ts +49 -0
  32. package/unstable-preview-types/legacy-network-handler/fetch-manager.d.ts.map +1 -0
  33. package/unstable-preview-types/legacy-network-handler/identifier-has-id.d.ts +5 -0
  34. package/unstable-preview-types/legacy-network-handler/identifier-has-id.d.ts.map +1 -0
  35. package/unstable-preview-types/legacy-network-handler/legacy-data-fetch.d.ts +15 -0
  36. package/unstable-preview-types/legacy-network-handler/legacy-data-fetch.d.ts.map +1 -0
  37. package/unstable-preview-types/legacy-network-handler/legacy-data-utils.d.ts +8 -0
  38. package/unstable-preview-types/legacy-network-handler/legacy-data-utils.d.ts.map +1 -0
  39. package/unstable-preview-types/legacy-network-handler/legacy-network-handler.d.ts +5 -0
  40. package/unstable-preview-types/legacy-network-handler/legacy-network-handler.d.ts.map +1 -0
  41. package/unstable-preview-types/legacy-network-handler/minimum-adapter-interface.d.ts +549 -0
  42. package/unstable-preview-types/legacy-network-handler/minimum-adapter-interface.d.ts.map +1 -0
  43. package/unstable-preview-types/legacy-network-handler/minimum-serializer-interface.d.ts +235 -0
  44. package/unstable-preview-types/legacy-network-handler/minimum-serializer-interface.d.ts.map +1 -0
  45. package/unstable-preview-types/legacy-network-handler/serializer-response.d.ts +9 -0
  46. package/unstable-preview-types/legacy-network-handler/serializer-response.d.ts.map +1 -0
  47. package/unstable-preview-types/legacy-network-handler/snapshot-record-array.d.ts +96 -0
  48. package/unstable-preview-types/legacy-network-handler/snapshot-record-array.d.ts.map +1 -0
  49. package/unstable-preview-types/legacy-network-handler/snapshot.d.ts +257 -0
  50. package/unstable-preview-types/legacy-network-handler/snapshot.d.ts.map +1 -0
  51. package/unstable-preview-types/legacy-network-handler/utils.d.ts +8 -0
  52. package/unstable-preview-types/legacy-network-handler/utils.d.ts.map +1 -0
  53. package/unstable-preview-types/utils.d.ts +161 -0
  54. package/unstable-preview-types/utils.d.ts.map +1 -0
  55. package/addon/-private.js +0 -1
  56. package/addon/fetch-manager-025964e9.js.map +0 -1
  57. package/addon/index.js +0 -673
  58. package/addon/index.js.map +0 -1
  59. package/addon-main.js +0 -93
  60. /package/{addon → dist}/-private.js.map +0 -0
package/dist/index.js ADDED
@@ -0,0 +1,1087 @@
1
+ import { getOwner } from '@ember/application';
2
+ import { deprecate } from '@ember/debug';
3
+ import { recordIdentifierFor } from '@ember-data/store';
4
+ import { g as guardDestroyedStore, _ as _objectIsAlive, p as payloadIsNotBlank, n as normalizeResponseHelper, a as _guard, i as iterateData, b as _bind, F as FetchManager, c as assertIdentifierHasId, S as SaveOp, d as SnapshotRecordArray } from "./-private-BJlhRRce.js";
5
+ import { n as normalizeModelName } from "./utils-XGHLsgBS.js";
6
+ import { macroCondition, getGlobalConfig, importSync } from '@embroider/macros';
7
+ function _findHasMany(adapter, store, identifier, link, relationship, options) {
8
+ let promise = Promise.resolve().then(() => {
9
+ const snapshot = store._fetchManager.createSnapshot(identifier, options);
10
+ const useLink = !link || typeof link === 'string';
11
+ const relatedLink = useLink ? link : link.href;
12
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
13
+ if (!test) {
14
+ throw new Error(`Attempted to load a hasMany relationship from a specified 'link' in the original payload, but the specified link is empty. You must provide a valid 'link' in the original payload to use 'findHasMany'`);
15
+ }
16
+ })(relatedLink) : {};
17
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
18
+ if (!test) {
19
+ throw new Error(`Expected the adapter to implement 'findHasMany' but it does not`);
20
+ }
21
+ })(typeof adapter.findHasMany === 'function') : {};
22
+ return adapter.findHasMany(store, snapshot, relatedLink, relationship);
23
+ });
24
+ promise = guardDestroyedStore(promise, store);
25
+ promise = promise.then(adapterPayload => {
26
+ const record = store._instanceCache.getRecord(identifier);
27
+ if (!_objectIsAlive(record)) {
28
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RSVP_PROMISE)) {
29
+ deprecate(`A Promise for fetching ${relationship.type} did not resolve by the time your model was destroyed. This will error in a future release.`, false, {
30
+ id: 'ember-data:rsvp-unresolved-async',
31
+ until: '5.0',
32
+ for: '@ember-data/store',
33
+ since: {
34
+ available: '4.5',
35
+ enabled: '4.5'
36
+ }
37
+ });
38
+ }
39
+ }
40
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
41
+ if (!test) {
42
+ throw new Error(`You made a 'findHasMany' request for a ${identifier.type}'s '${relationship.name}' relationship, using link '${JSON.stringify(link)}' , but the adapter's response did not have any data`);
43
+ }
44
+ })(payloadIsNotBlank(adapterPayload)) : {};
45
+ const modelClass = store.modelFor(relationship.type);
46
+ const serializer = store.serializerFor(relationship.type);
47
+ let payload = normalizeResponseHelper(serializer, store, modelClass, adapterPayload, null, 'findHasMany');
48
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
49
+ if (!test) {
50
+ throw new Error(`fetched the hasMany relationship '${relationship.name}' for ${identifier.type}:${identifier.id} with link '${JSON.stringify(link)}', but no data member is present in the response. If no data exists, the response should set { data: [] }`);
51
+ }
52
+ })('data' in payload && Array.isArray(payload.data)) : {};
53
+ payload = syncRelationshipDataFromLink(store, payload, identifier, relationship);
54
+ return store._push(payload, true);
55
+ }, null);
56
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RSVP_PROMISE)) {
57
+ const record = store._instanceCache.getRecord(identifier);
58
+ promise = _guard(promise, _bind(_objectIsAlive, record));
59
+ }
60
+ return promise;
61
+ }
62
+ function _findBelongsTo(store, identifier, link, relationship, options) {
63
+ let promise = Promise.resolve().then(() => {
64
+ const adapter = store.adapterFor(identifier.type);
65
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
66
+ if (!test) {
67
+ throw new Error(`You tried to load a belongsTo relationship but you have no adapter (for ${identifier.type})`);
68
+ }
69
+ })(adapter) : {};
70
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
71
+ if (!test) {
72
+ throw new Error(`You tried to load a belongsTo relationship from a specified 'link' in the original payload but your adapter does not implement 'findBelongsTo'`);
73
+ }
74
+ })(typeof adapter.findBelongsTo === 'function') : {};
75
+ const snapshot = store._fetchManager.createSnapshot(identifier, options);
76
+ const useLink = !link || typeof link === 'string';
77
+ const relatedLink = useLink ? link : link.href;
78
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
79
+ if (!test) {
80
+ throw new Error(`Attempted to load a belongsTo relationship from a specified 'link' in the original payload, but the specified link is empty. You must provide a valid 'link' in the original payload to use 'findBelongsTo'`);
81
+ }
82
+ })(relatedLink) : {};
83
+ return adapter.findBelongsTo(store, snapshot, relatedLink, relationship);
84
+ });
85
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RSVP_PROMISE)) {
86
+ const record = store._instanceCache.getRecord(identifier);
87
+ promise = guardDestroyedStore(promise, store);
88
+ promise = _guard(promise, _bind(_objectIsAlive, record));
89
+ }
90
+ return promise.then(adapterPayload => {
91
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RSVP_PROMISE)) {
92
+ const record = store._instanceCache.getRecord(identifier);
93
+ if (!_objectIsAlive(record)) {
94
+ deprecate(`A Promise for fetching ${relationship.type} did not resolve by the time your model was destroyed. This will error in a future release.`, false, {
95
+ id: 'ember-data:rsvp-unresolved-async',
96
+ until: '5.0',
97
+ for: '@ember-data/store',
98
+ since: {
99
+ available: '4.5',
100
+ enabled: '4.5'
101
+ }
102
+ });
103
+ }
104
+ }
105
+ const modelClass = store.modelFor(relationship.type);
106
+ const serializer = store.serializerFor(relationship.type);
107
+ let payload = normalizeResponseHelper(serializer, store, modelClass, adapterPayload, null, 'findBelongsTo');
108
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
109
+ if (!test) {
110
+ throw new Error(`fetched the belongsTo relationship '${relationship.name}' for ${identifier.type}:${identifier.id} with link '${JSON.stringify(link)}', but no data member is present in the response. If no data exists, the response should set { data: null }`);
111
+ }
112
+ })('data' in payload && (payload.data === null || typeof payload.data === 'object' && !Array.isArray(payload.data))) : {};
113
+ if (!payload.data && !payload.links && !payload.meta) {
114
+ return null;
115
+ }
116
+ payload = syncRelationshipDataFromLink(store, payload, identifier, relationship);
117
+ return store._push(payload, true);
118
+ }, null);
119
+ }
120
+
121
+ // sync
122
+ // iterate over records in payload.data
123
+ // for each record
124
+ // assert that record.relationships[inverse] is either undefined (so we can fix it)
125
+ // or provide a data: {id, type} that matches the record that requested it
126
+ // return the relationship data for the parent
127
+ function syncRelationshipDataFromLink(store, payload, parentIdentifier, relationship) {
128
+ // ensure the right hand side (incoming payload) points to the parent record that
129
+ // requested this relationship
130
+ const relationshipData = payload.data ? iterateData(payload.data, (data, index) => {
131
+ const {
132
+ id,
133
+ type
134
+ } = data;
135
+ ensureRelationshipIsSetToParent(data, parentIdentifier, store, relationship, index);
136
+ return {
137
+ id,
138
+ type
139
+ };
140
+ }) : null;
141
+ const relatedDataHash = {};
142
+ if ('meta' in payload) {
143
+ relatedDataHash.meta = payload.meta;
144
+ }
145
+ if ('links' in payload) {
146
+ relatedDataHash.links = payload.links;
147
+ }
148
+ if ('data' in payload) {
149
+ relatedDataHash.data = relationshipData;
150
+ }
151
+
152
+ // now, push the left hand side (the parent record) to ensure things are in sync, since
153
+ // the payload will be pushed with store._push
154
+ const parentPayload = {
155
+ id: parentIdentifier.id,
156
+ type: parentIdentifier.type,
157
+ relationships: {
158
+ [relationship.name]: relatedDataHash
159
+ }
160
+ };
161
+ if (!Array.isArray(payload.included)) {
162
+ payload.included = [];
163
+ }
164
+ payload.included.push(parentPayload);
165
+ return payload;
166
+ }
167
+ function ensureRelationshipIsSetToParent(payload, parentIdentifier, store, parentRelationship, index) {
168
+ const {
169
+ id,
170
+ type
171
+ } = payload;
172
+ if (!payload.relationships) {
173
+ payload.relationships = {};
174
+ }
175
+ const {
176
+ relationships
177
+ } = payload;
178
+ const inverse = getInverse(store, parentIdentifier, parentRelationship, type);
179
+ if (inverse) {
180
+ const {
181
+ inverseKey,
182
+ kind
183
+ } = inverse;
184
+ const relationshipData = relationships[inverseKey]?.data;
185
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
186
+ if (typeof relationshipData !== 'undefined' && !relationshipDataPointsToParent(relationshipData, parentIdentifier)) {
187
+ const inspect = function inspect(thing) {
188
+ return `'${JSON.stringify(thing)}'`;
189
+ };
190
+ const quotedType = inspect(type);
191
+ const quotedInverse = inspect(inverseKey);
192
+ const expected = inspect({
193
+ id: parentIdentifier.id,
194
+ type: parentIdentifier.type
195
+ });
196
+ const expectedModel = `${parentIdentifier.type}:${parentIdentifier.id}`;
197
+ const got = inspect(relationshipData);
198
+ const prefix = typeof index === 'number' ? `data[${index}]` : `data`;
199
+ const path = `${prefix}.relationships.${inverseKey}.data`;
200
+ const data = Array.isArray(relationshipData) ? relationshipData[0] : relationshipData;
201
+ const other = data ? `<${data.type}:${data.id}>` : null;
202
+ const relationshipFetched = `${expectedModel}.${parentRelationship.kind}("${parentRelationship.name}")`;
203
+ const includedRecord = `<${type}:${id}>`;
204
+ const message = [`Encountered mismatched relationship: Ember Data expected ${path} in the payload from ${relationshipFetched} to include ${expected} but got ${got} instead.\n`, `The ${includedRecord} record loaded at ${prefix} in the payload specified ${other} as its ${quotedInverse}, but should have specified ${expectedModel} (the record the relationship is being loaded from) as its ${quotedInverse} instead.`, `This could mean that the response for ${relationshipFetched} may have accidentally returned ${quotedType} records that aren't related to ${expectedModel} and could be related to a different ${parentIdentifier.type} record instead.`, `Ember Data has corrected the ${includedRecord} record's ${quotedInverse} relationship to ${expectedModel} so that ${relationshipFetched} will include ${includedRecord}.`, `Please update the response from the server or change your serializer to either ensure that the response for only includes ${quotedType} records that specify ${expectedModel} as their ${quotedInverse}, or omit the ${quotedInverse} relationship from the response.`].join('\n');
205
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
206
+ {
207
+ throw new Error(message);
208
+ }
209
+ })() : {};
210
+ }
211
+ }
212
+ if (kind !== 'hasMany' || typeof relationshipData !== 'undefined') {
213
+ relationships[inverseKey] = relationships[inverseKey] || {};
214
+ relationships[inverseKey].data = fixRelationshipData(relationshipData ?? null, kind, parentIdentifier);
215
+ }
216
+ }
217
+ }
218
+ function metaIsRelationshipDefinition(meta) {
219
+ return typeof meta === 'object' && !!meta && '_inverseKey' in meta && typeof meta._inverseKey === 'function';
220
+ }
221
+ function inverseForRelationship(store, identifier, key) {
222
+ const definition = store.schema.fields(identifier).get(key);
223
+ if (!definition) {
224
+ return null;
225
+ }
226
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_RELATIONSHIPS_WITHOUT_INVERSE)) {
227
+ if (metaIsRelationshipDefinition(definition)) {
228
+ const modelClass = store.modelFor(identifier.type);
229
+ return definition._inverseKey(store, modelClass);
230
+ }
231
+ }
232
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
233
+ if (!test) {
234
+ throw new Error(`Expected the field definition to be a relationship`);
235
+ }
236
+ })(definition.kind === 'hasMany' || definition.kind === 'belongsTo') : {};
237
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
238
+ if (!test) {
239
+ throw new Error(`Expected the relationship defintion to specify the inverse type or null.`);
240
+ }
241
+ })(definition.options?.inverse === null || typeof definition.options?.inverse === 'string' && definition.options.inverse.length > 0) : {};
242
+ return definition.options.inverse;
243
+ }
244
+ function getInverse(store, parentIdentifier, parentRelationship, type) {
245
+ const {
246
+ name: lhs_relationshipName
247
+ } = parentRelationship;
248
+ const {
249
+ type: parentType
250
+ } = parentIdentifier;
251
+ const inverseKey = inverseForRelationship(store, {
252
+ type: parentType
253
+ }, lhs_relationshipName);
254
+ if (inverseKey) {
255
+ const definition = store.schema.fields({
256
+ type
257
+ }).get(inverseKey);
258
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
259
+ if (!test) {
260
+ throw new Error(`Expected the field definition to be a relationship`);
261
+ }
262
+ })(definition && (definition.kind === 'hasMany' || definition.kind === 'belongsTo')) : {};
263
+ return {
264
+ inverseKey,
265
+ kind: definition.kind
266
+ };
267
+ }
268
+ }
269
+ function relationshipDataPointsToParent(relationshipData, identifier) {
270
+ if (relationshipData === null) {
271
+ return false;
272
+ }
273
+ if (Array.isArray(relationshipData)) {
274
+ if (relationshipData.length === 0) {
275
+ return false;
276
+ }
277
+ for (let i = 0; i < relationshipData.length; i++) {
278
+ const entry = relationshipData[i];
279
+ if (validateRelationshipEntry(entry, identifier)) {
280
+ return true;
281
+ }
282
+ }
283
+ } else {
284
+ return validateRelationshipEntry(relationshipData, identifier);
285
+ }
286
+ return false;
287
+ }
288
+ function fixRelationshipData(relationshipData, relationshipKind, {
289
+ id,
290
+ type
291
+ }) {
292
+ const parentRelationshipData = {
293
+ id,
294
+ type
295
+ };
296
+ let payload = null;
297
+ if (relationshipKind === 'hasMany') {
298
+ const relData = relationshipData || [];
299
+ if (relationshipData) {
300
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
301
+ if (!test) {
302
+ throw new Error('expected the relationship data to be an array');
303
+ }
304
+ })(Array.isArray(relationshipData)) : {};
305
+ // these arrays could be massive so this is better than filter
306
+ // Note: this is potentially problematic if type/id are not in the
307
+ // same state of normalization.
308
+ const found = relationshipData.find(v => {
309
+ return v.type === parentRelationshipData.type && v.id === parentRelationshipData.id;
310
+ });
311
+ if (!found) {
312
+ relData.push(parentRelationshipData);
313
+ }
314
+ } else {
315
+ relData.push(parentRelationshipData);
316
+ }
317
+ payload = relData;
318
+ } else {
319
+ const relData = relationshipData || {};
320
+ Object.assign(relData, parentRelationshipData);
321
+ payload = relData;
322
+ }
323
+ return payload;
324
+ }
325
+ function validateRelationshipEntry({
326
+ id
327
+ }, {
328
+ id: parentModelID
329
+ }) {
330
+ return !!id && id.toString() === parentModelID;
331
+ }
332
+ const PotentialLegacyOperations = new Set(['findRecord', 'findAll', 'query', 'queryRecord', 'findBelongsTo', 'findHasMany', 'updateRecord', 'createRecord', 'deleteRecord']);
333
+ const LegacyNetworkHandler = {
334
+ request(context, next) {
335
+ // if we are not a legacy request, move on
336
+ if (context.request.url || !context.request.op || !PotentialLegacyOperations.has(context.request.op)) {
337
+ return next(context.request);
338
+ }
339
+ const {
340
+ store
341
+ } = context.request;
342
+ if (!store._fetchManager) {
343
+ store._fetchManager = new FetchManager(store);
344
+ }
345
+ switch (context.request.op) {
346
+ case 'findRecord':
347
+ return findRecord(context);
348
+ case 'findAll':
349
+ return findAll(context);
350
+ case 'query':
351
+ return query(context);
352
+ case 'queryRecord':
353
+ return queryRecord(context);
354
+ case 'findBelongsTo':
355
+ return findBelongsTo(context);
356
+ case 'findHasMany':
357
+ return findHasMany(context);
358
+ case 'updateRecord':
359
+ return saveRecord(context);
360
+ case 'createRecord':
361
+ return saveRecord(context);
362
+ case 'deleteRecord':
363
+ return saveRecord(context);
364
+ default:
365
+ return next(context.request);
366
+ }
367
+ }
368
+ };
369
+ function findBelongsTo(context) {
370
+ const {
371
+ store,
372
+ data,
373
+ records: identifiers
374
+ } = context.request;
375
+ const {
376
+ options,
377
+ record,
378
+ links,
379
+ useLink,
380
+ field
381
+ } = data;
382
+ const identifier = identifiers?.[0];
383
+
384
+ // short circuit if we are already loading
385
+ const pendingRequest = identifier && store._fetchManager.getPendingFetch(identifier, options);
386
+ if (pendingRequest) {
387
+ return pendingRequest;
388
+ }
389
+ if (useLink) {
390
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
391
+ if (!test) {
392
+ throw new Error(`Expected a related link when calling store.findBelongsTo, found ${String(links)}`);
393
+ }
394
+ })(links && links.related) : {};
395
+ return _findBelongsTo(store, record, links.related, field, options);
396
+ }
397
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
398
+ if (!test) {
399
+ throw new Error(`Expected an identifier`);
400
+ }
401
+ })(Array.isArray(identifiers) && identifiers.length === 1) : {};
402
+ const manager = store._fetchManager;
403
+ assertIdentifierHasId(identifier);
404
+ return options.reload ? manager.scheduleFetch(identifier, options, context.request) : manager.fetchDataIfNeededForIdentifier(identifier, options, context.request);
405
+ }
406
+ function findHasMany(context) {
407
+ const {
408
+ store,
409
+ data,
410
+ records: identifiers
411
+ } = context.request;
412
+ const {
413
+ options,
414
+ record,
415
+ links,
416
+ useLink,
417
+ field
418
+ } = data;
419
+
420
+ // link case
421
+ if (useLink) {
422
+ const adapter = store.adapterFor(record.type);
423
+ /*
424
+ If a relationship was originally populated by the adapter as a link
425
+ (as opposed to a list of IDs), this method is called when the
426
+ relationship is fetched.
427
+ The link (which is usually a URL) is passed through unchanged, so the
428
+ adapter can make whatever request it wants.
429
+ The usual use-case is for the server to register a URL as a link, and
430
+ then use that URL in the future to make a request for the relationship.
431
+ */
432
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
433
+ if (!test) {
434
+ throw new Error(`You tried to load a hasMany relationship but you have no adapter (for ${record.type})`);
435
+ }
436
+ })(adapter) : {};
437
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
438
+ if (!test) {
439
+ throw new Error(`You tried to load a hasMany relationship from a specified 'link' in the original payload but your adapter does not implement 'findHasMany'`);
440
+ }
441
+ })(typeof adapter.findHasMany === 'function') : {};
442
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
443
+ if (!test) {
444
+ throw new Error(`Expected a related link when calling store.findHasMany, found ${String(links)}`);
445
+ }
446
+ })(links && links.related) : {};
447
+ return _findHasMany(adapter, store, record, links.related, field, options);
448
+ }
449
+
450
+ // identifiers case
451
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
452
+ if (!test) {
453
+ throw new Error(`Expected an array of identifiers to fetch`);
454
+ }
455
+ })(Array.isArray(identifiers)) : {};
456
+ const fetches = new Array(identifiers.length);
457
+ const manager = store._fetchManager;
458
+ for (let i = 0; i < identifiers.length; i++) {
459
+ const identifier = identifiers[i];
460
+ // TODO we probably can be lenient here and return from cache for the isNew case
461
+ assertIdentifierHasId(identifier);
462
+ fetches[i] = options.reload ? manager.scheduleFetch(identifier, options, context.request) : manager.fetchDataIfNeededForIdentifier(identifier, options, context.request);
463
+ }
464
+ return Promise.all(fetches);
465
+ }
466
+ function saveRecord(context) {
467
+ const {
468
+ store,
469
+ data,
470
+ op: operation
471
+ } = context.request;
472
+ const {
473
+ options,
474
+ record: identifier
475
+ } = data;
476
+ store.cache.willCommit(identifier, context);
477
+ const saveOptions = Object.assign({
478
+ [SaveOp]: operation
479
+ }, options);
480
+ const fetchManagerPromise = store._fetchManager.scheduleSave(identifier, saveOptions);
481
+ return fetchManagerPromise.then(payload => {
482
+ if (macroCondition(getGlobalConfig().WarpDrive.debug.LOG_PAYLOADS)) {
483
+ try {
484
+ const payloadCopy = payload ? JSON.parse(JSON.stringify(payload)) : payload;
485
+ // eslint-disable-next-line no-console
486
+ console.log(`EmberData | Payload - ${operation}`, payloadCopy);
487
+ } catch {
488
+ // eslint-disable-next-line no-console
489
+ console.log(`EmberData | Payload - ${operation}`, payload);
490
+ }
491
+ }
492
+ let result;
493
+ store._join(() => {
494
+ // @ts-expect-error we don't have access to a response in legacy
495
+ result = store.cache.didCommit(identifier, {
496
+ request: context.request,
497
+ content: payload
498
+ });
499
+ });
500
+
501
+ // blatantly lie if we were a createRecord request
502
+ // to give some semblance of cache-control to the
503
+ // CachePolicy while legacy is still around
504
+ if (store.lifetimes?.didRequest && operation === 'createRecord') {
505
+ store.lifetimes.didRequest(context.request, {
506
+ status: 201
507
+ }, null, store);
508
+ }
509
+ return store.peekRecord(result.data);
510
+ }).catch(e => {
511
+ let err = e;
512
+ if (!e) {
513
+ err = new Error(`Unknown Error Occurred During Request`);
514
+ } else if (typeof e === 'string') {
515
+ err = new Error(e);
516
+ }
517
+ adapterDidInvalidate(store, identifier, err);
518
+ throw err;
519
+ });
520
+ }
521
+ function adapterDidInvalidate(store, identifier, error) {
522
+ if (error && error.isAdapterError === true && error.code === 'InvalidError') {
523
+ const serializer = store.serializerFor(identifier.type);
524
+
525
+ // TODO @deprecate extractErrors being called
526
+ // TODO remove extractErrors from the default serializers.
527
+ if (serializer && typeof serializer.extractErrors === 'function') {
528
+ const errorsHash = serializer.extractErrors(store, store.modelFor(identifier.type), error, identifier.id);
529
+ error.errors = errorsHashToArray(errorsHash);
530
+ }
531
+ }
532
+ const cache = store.cache;
533
+ if (error.errors) {
534
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
535
+ if (!test) {
536
+ throw new Error(`Expected the cache in use by resource ${String(identifier)} to have a getErrors(identifier) method for retrieving errors.`);
537
+ }
538
+ })(typeof cache.getErrors === 'function') : {};
539
+ let jsonApiErrors = error.errors;
540
+ if (jsonApiErrors.length === 0) {
541
+ jsonApiErrors = [{
542
+ title: 'Invalid Error',
543
+ detail: '',
544
+ source: {
545
+ pointer: '/data'
546
+ }
547
+ }];
548
+ }
549
+ cache.commitWasRejected(identifier, jsonApiErrors);
550
+ } else {
551
+ cache.commitWasRejected(identifier);
552
+ }
553
+ }
554
+ function makeArray(value) {
555
+ return Array.isArray(value) ? value : [value];
556
+ }
557
+ const PRIMARY_ATTRIBUTE_KEY = 'base';
558
+ function errorsHashToArray(errors) {
559
+ const out = [];
560
+ if (errors) {
561
+ Object.keys(errors).forEach(key => {
562
+ const messages = makeArray(errors[key]);
563
+ for (let i = 0; i < messages.length; i++) {
564
+ let title = 'Invalid Attribute';
565
+ let pointer = `/data/attributes/${key}`;
566
+ if (key === PRIMARY_ATTRIBUTE_KEY) {
567
+ title = 'Invalid Document';
568
+ pointer = `/data`;
569
+ }
570
+ out.push({
571
+ title: title,
572
+ detail: messages[i],
573
+ source: {
574
+ pointer: pointer
575
+ }
576
+ });
577
+ }
578
+ });
579
+ }
580
+ return out;
581
+ }
582
+ function findRecord(context) {
583
+ const {
584
+ store,
585
+ data
586
+ } = context.request;
587
+ const {
588
+ record: identifier,
589
+ options
590
+ } = data;
591
+ let promise;
592
+
593
+ // if not loaded start loading
594
+ if (!store._instanceCache.recordIsLoaded(identifier)) {
595
+ promise = store._fetchManager.fetchDataIfNeededForIdentifier(identifier, options, context.request);
596
+
597
+ // Refetch if the reload option is passed
598
+ } else if (options.reload) {
599
+ assertIdentifierHasId(identifier);
600
+ promise = store._fetchManager.scheduleFetch(identifier, options, context.request);
601
+ } else {
602
+ let snapshot = null;
603
+ const adapter = store.adapterFor(identifier.type);
604
+
605
+ // Refetch the record if the adapter thinks the record is stale
606
+ if (typeof options.reload === 'undefined' && adapter.shouldReloadRecord && adapter.shouldReloadRecord(store, snapshot = store._fetchManager.createSnapshot(identifier, options))) {
607
+ assertIdentifierHasId(identifier);
608
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
609
+ promise = store._fetchManager.scheduleFetch(identifier, Object.assign({}, options, {
610
+ reload: true
611
+ }), context.request);
612
+ } else {
613
+ options.reload = true;
614
+ promise = store._fetchManager.scheduleFetch(identifier, options, context.request);
615
+ }
616
+ } else {
617
+ // Trigger the background refetch if backgroundReload option is passed
618
+ if (options.backgroundReload !== false && (options.backgroundReload || !adapter.shouldBackgroundReloadRecord || adapter.shouldBackgroundReloadRecord(store, snapshot = snapshot || store._fetchManager.createSnapshot(identifier, options)))) {
619
+ assertIdentifierHasId(identifier);
620
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
621
+ void store._fetchManager.scheduleFetch(identifier, Object.assign({}, options, {
622
+ backgroundReload: true
623
+ }), context.request);
624
+ } else {
625
+ options.backgroundReload = true;
626
+ void store._fetchManager.scheduleFetch(identifier, options, context.request);
627
+ }
628
+ }
629
+
630
+ // Return the cached record
631
+ promise = Promise.resolve(identifier);
632
+ }
633
+ }
634
+ return promise.then(i => store.peekRecord(i));
635
+ }
636
+ function findAll(context) {
637
+ const {
638
+ store,
639
+ data
640
+ } = context.request;
641
+ const {
642
+ type,
643
+ options
644
+ } = data;
645
+ const adapter = store.adapterFor(type);
646
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
647
+ if (!test) {
648
+ throw new Error(`You tried to load all records but you have no adapter (for ${type})`);
649
+ }
650
+ })(adapter) : {};
651
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
652
+ if (!test) {
653
+ throw new Error(`You tried to load all records but your adapter does not implement 'findAll'`);
654
+ }
655
+ })(typeof adapter.findAll === 'function') : {};
656
+
657
+ // avoid initializing the liveArray just to set `isUpdating`
658
+ const maybeRecordArray = store.recordArrayManager._live.get(type);
659
+ const snapshotArray = new SnapshotRecordArray(store, type, options);
660
+ const shouldReload = options.reload || options.reload !== false && (adapter.shouldReloadAll && adapter.shouldReloadAll(store, snapshotArray) || !adapter.shouldReloadAll && snapshotArray.length === 0);
661
+ let fetch;
662
+ if (shouldReload) {
663
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
664
+ maybeRecordArray && (maybeRecordArray.isUpdating = true);
665
+ fetch = _findAll(adapter, store, type, snapshotArray, context.request, true);
666
+ } else {
667
+ fetch = Promise.resolve(store.peekAll(type));
668
+ if (options.backgroundReload || options.backgroundReload !== false && (!adapter.shouldBackgroundReloadAll || adapter.shouldBackgroundReloadAll(store, snapshotArray))) {
669
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
670
+ maybeRecordArray && (maybeRecordArray.isUpdating = true);
671
+ void _findAll(adapter, store, type, snapshotArray, context.request, false);
672
+ }
673
+ }
674
+ return fetch;
675
+ }
676
+ function _findAll(adapter, store, type, snapshotArray, request, isAsyncFlush) {
677
+ const schema = store.modelFor(type);
678
+ let promise = Promise.resolve().then(() => adapter.findAll(store, schema, null, snapshotArray));
679
+ promise = promise.then(adapterPayload => {
680
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
681
+ if (!test) {
682
+ throw new Error(`You made a 'findAll' request for '${type}' records, but the adapter's response did not have any data`);
683
+ }
684
+ })(payloadIsNotBlank(adapterPayload)) : {};
685
+ const serializer = store.serializerFor(type);
686
+ const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'findAll');
687
+ store._push(payload, isAsyncFlush);
688
+ snapshotArray._recordArray.isUpdating = false;
689
+ if (macroCondition(getGlobalConfig().WarpDrive.debug.LOG_PAYLOADS)) {
690
+ // eslint-disable-next-line no-console
691
+ console.log(`request: findAll<${type}> background reload complete`);
692
+ }
693
+ return snapshotArray._recordArray;
694
+ });
695
+ if (macroCondition(getGlobalConfig().WarpDrive.env.TESTING)) {
696
+ if (!request.disableTestWaiter) {
697
+ const {
698
+ waitForPromise
699
+ } = importSync('@ember/test-waiters');
700
+ promise = waitForPromise(promise);
701
+ }
702
+ }
703
+ return promise;
704
+ }
705
+ function query(context) {
706
+ const {
707
+ store,
708
+ data
709
+ } = context.request;
710
+ let {
711
+ options
712
+ } = data;
713
+ // eslint-disable-next-line @typescript-eslint/no-shadow
714
+ const {
715
+ type,
716
+ query
717
+ } = data;
718
+ const adapter = store.adapterFor(type);
719
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
720
+ if (!test) {
721
+ throw new Error(`You tried to make a query but you have no adapter (for ${type})`);
722
+ }
723
+ })(adapter) : {};
724
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
725
+ if (!test) {
726
+ throw new Error(`You tried to make a query but your adapter does not implement 'query'`);
727
+ }
728
+ })(typeof adapter.query === 'function') : {};
729
+ const recordArray = options._recordArray || store.recordArrayManager.createArray({
730
+ type,
731
+ query
732
+ });
733
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
734
+ options = Object.assign({}, options);
735
+ delete options._recordArray;
736
+ } else {
737
+ delete options._recordArray;
738
+ }
739
+ const schema = store.modelFor(type);
740
+ const promise = Promise.resolve().then(() => adapter.query(store, schema, query, recordArray, options));
741
+ return promise.then(adapterPayload => {
742
+ const serializer = store.serializerFor(type);
743
+ const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'query');
744
+ const identifiers = store._push(payload, true);
745
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
746
+ if (!test) {
747
+ throw new Error('The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use `store.queryRecord` to query for a single record.');
748
+ }
749
+ })(Array.isArray(identifiers)) : {};
750
+ store.recordArrayManager.populateManagedArray(recordArray, identifiers, payload);
751
+ return recordArray;
752
+ });
753
+ }
754
+ function assertSingleResourceDocument(payload) {
755
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
756
+ if (!test) {
757
+ throw new Error(`Expected the primary data returned by the serializer for a 'queryRecord' response to be a single object or null but instead it was an array.`);
758
+ }
759
+ })(!Array.isArray(payload.data)) : {};
760
+ }
761
+ function queryRecord(context) {
762
+ const {
763
+ store,
764
+ data
765
+ } = context.request;
766
+ // eslint-disable-next-line @typescript-eslint/no-shadow
767
+ const {
768
+ type,
769
+ query,
770
+ options
771
+ } = data;
772
+ const adapter = store.adapterFor(type);
773
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
774
+ if (!test) {
775
+ throw new Error(`You tried to make a query but you have no adapter (for ${type})`);
776
+ }
777
+ })(adapter) : {};
778
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
779
+ if (!test) {
780
+ throw new Error(`You tried to make a query but your adapter does not implement 'queryRecord'`);
781
+ }
782
+ })(typeof adapter.queryRecord === 'function') : {};
783
+ const schema = store.modelFor(type);
784
+ const promise = Promise.resolve().then(() => adapter.queryRecord(store, schema, query, options));
785
+ return promise.then(adapterPayload => {
786
+ const serializer = store.serializerFor(type);
787
+ const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'queryRecord');
788
+ assertSingleResourceDocument(payload);
789
+ const identifier = store._push(payload, true);
790
+ return identifier ? store.peekRecord(identifier) : null;
791
+ });
792
+ }
793
+
794
+ /**
795
+ * @module @ember-data/store
796
+ * @class Store
797
+ */
798
+
799
+ /**
800
+ Returns an instance of the adapter for a given type. For
801
+ example, `adapterFor('person')` will return an instance of
802
+ the adapter located at `app/adapters/person.js`
803
+
804
+ If no `person` adapter is found, this method will look
805
+ for an `application` adapter (the default adapter for
806
+ your entire application).
807
+
808
+ @method adapterFor
809
+ @public
810
+ @param {String} modelName
811
+ @return Adapter
812
+ */
813
+
814
+ function adapterFor(modelName, _allowMissing) {
815
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
816
+ if (!test) {
817
+ throw new Error(`Attempted to call store.adapterFor(), but the store instance has already been destroyed.`);
818
+ }
819
+ })(!(this.isDestroying || this.isDestroyed)) : {};
820
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
821
+ if (!test) {
822
+ throw new Error(`You need to pass a model name to the store's adapterFor method`);
823
+ }
824
+ })(modelName) : {};
825
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
826
+ if (!test) {
827
+ throw new Error(`Passing classes to store.adapterFor has been removed. Please pass a dasherized string instead of ${modelName}`);
828
+ }
829
+ })(typeof modelName === 'string') : {};
830
+ this._adapterCache = this._adapterCache || Object.create(null);
831
+ const normalizedModelName = normalizeModelName(modelName);
832
+ const {
833
+ _adapterCache
834
+ } = this;
835
+ let adapter = _adapterCache[normalizedModelName];
836
+ if (adapter) {
837
+ return adapter;
838
+ }
839
+ const owner = getOwner(this);
840
+
841
+ // name specific adapter
842
+ adapter = owner.lookup(`adapter:${normalizedModelName}`);
843
+ if (adapter !== undefined) {
844
+ _adapterCache[normalizedModelName] = adapter;
845
+ return adapter;
846
+ }
847
+
848
+ // no adapter found for the specific name, fallback and check for application adapter
849
+ adapter = _adapterCache.application || owner.lookup('adapter:application');
850
+ if (adapter !== undefined) {
851
+ _adapterCache[normalizedModelName] = adapter;
852
+ _adapterCache.application = adapter;
853
+ return adapter;
854
+ }
855
+ if (macroCondition(getGlobalConfig().WarpDrive.deprecations.DEPRECATE_JSON_API_FALLBACK)) {
856
+ // final fallback, no model specific adapter, no application adapter, no
857
+ // `adapter` property on store: use json-api adapter
858
+ adapter = _adapterCache['-json-api'] || owner.lookup('adapter:-json-api');
859
+ if (adapter !== undefined) {
860
+ deprecate(`Your application is utilizing a deprecated hidden fallback adapter (-json-api). Please implement an application adapter to function as your fallback.`, false, {
861
+ id: 'ember-data:deprecate-secret-adapter-fallback',
862
+ for: 'ember-data',
863
+ until: '5.0',
864
+ since: {
865
+ available: '4.5',
866
+ enabled: '4.5'
867
+ }
868
+ });
869
+ _adapterCache[normalizedModelName] = adapter;
870
+ _adapterCache['-json-api'] = adapter;
871
+ return adapter;
872
+ }
873
+ }
874
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
875
+ if (!test) {
876
+ throw new Error(`No adapter was found for '${modelName}' and no 'application' adapter was found as a fallback.`);
877
+ }
878
+ })(_allowMissing) : {};
879
+ }
880
+
881
+ /**
882
+ Returns an instance of the serializer for a given type. For
883
+ example, `serializerFor('person')` will return an instance of
884
+ `App.PersonSerializer`.
885
+
886
+ If no `App.PersonSerializer` is found, this method will look
887
+ for an `App.ApplicationSerializer` (the default serializer for
888
+ your entire application).
889
+
890
+ If a serializer cannot be found on the adapter, it will fall back
891
+ to an instance of `JSONSerializer`.
892
+
893
+ @method serializerFor
894
+ @public
895
+ @param {String} modelName the record to serialize
896
+ @return {Serializer}
897
+ */
898
+ function serializerFor(modelName) {
899
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
900
+ if (!test) {
901
+ throw new Error(`Attempted to call store.serializerFor(), but the store instance has already been destroyed.`);
902
+ }
903
+ })(!(this.isDestroying || this.isDestroyed)) : {};
904
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
905
+ if (!test) {
906
+ throw new Error(`You need to pass a model name to the store's serializerFor method`);
907
+ }
908
+ })(modelName) : {};
909
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
910
+ if (!test) {
911
+ throw new Error(`Passing classes to store.serializerFor has been removed. Please pass a dasherized string instead of ${modelName}`);
912
+ }
913
+ })(typeof modelName === 'string') : {};
914
+ this._serializerCache = this._serializerCache || Object.create(null);
915
+ const normalizedModelName = normalizeModelName(modelName);
916
+ const {
917
+ _serializerCache
918
+ } = this;
919
+ let serializer = _serializerCache[normalizedModelName];
920
+ if (serializer) {
921
+ return serializer;
922
+ }
923
+
924
+ // by name
925
+ const owner = getOwner(this);
926
+ serializer = owner.lookup(`serializer:${normalizedModelName}`);
927
+ if (serializer !== undefined) {
928
+ _serializerCache[normalizedModelName] = serializer;
929
+ return serializer;
930
+ }
931
+
932
+ // no serializer found for the specific model, fallback and check for application serializer
933
+ serializer = _serializerCache.application || owner.lookup('serializer:application');
934
+ if (serializer !== undefined) {
935
+ _serializerCache[normalizedModelName] = serializer;
936
+ _serializerCache.application = serializer;
937
+ return serializer;
938
+ }
939
+ return null;
940
+ }
941
+
942
+ /**
943
+ `normalize` converts a json payload into the normalized form that
944
+ [push](../methods/push?anchor=push) expects.
945
+
946
+ Example
947
+
948
+ ```js
949
+ socket.on('message', function(message) {
950
+ let modelName = message.model;
951
+ let data = message.data;
952
+ store.push(store.normalize(modelName, data));
953
+ });
954
+ ```
955
+
956
+ @method normalize
957
+ @public
958
+ @param {String} modelName The name of the model type for this payload
959
+ @param {Object} payload
960
+ @return {Object} The normalized payload
961
+ */
962
+ // TODO @runspired @deprecate users should call normalize on the associated serializer directly
963
+ function normalize(modelName, payload) {
964
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
965
+ if (!test) {
966
+ throw new Error(`Attempted to call store.normalize(), but the store instance has already been destroyed.`);
967
+ }
968
+ })(!(this.isDestroying || this.isDestroyed)) : {};
969
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
970
+ if (!test) {
971
+ throw new Error(`You need to pass a model name to the store's normalize method`);
972
+ }
973
+ })(modelName) : {};
974
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
975
+ if (!test) {
976
+ throw new Error(`Passing classes to store methods has been removed. Please pass a dasherized string instead of ${typeof modelName}`);
977
+ }
978
+ })(typeof modelName === 'string') : {};
979
+ const normalizedModelName = normalizeModelName(modelName);
980
+ const serializer = this.serializerFor(normalizedModelName);
981
+ const schema = this.modelFor(normalizedModelName);
982
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
983
+ if (!test) {
984
+ throw new Error(`You must define a normalize method in your serializer in order to call store.normalize`);
985
+ }
986
+ })(typeof serializer?.normalize === 'function') : {};
987
+ return serializer.normalize(schema, payload);
988
+ }
989
+
990
+ /**
991
+ Push some raw data into the store.
992
+
993
+ This method can be used both to push in brand new
994
+ records, as well as to update existing records. You
995
+ can push in more than one type of object at once.
996
+ All objects should be in the format expected by the
997
+ serializer.
998
+
999
+ ```app/serializers/application.js
1000
+ import RESTSerializer from '@ember-data/serializer/rest';
1001
+
1002
+ export default class ApplicationSerializer extends RESTSerializer;
1003
+ ```
1004
+
1005
+ ```js
1006
+ let pushData = {
1007
+ posts: [
1008
+ { id: 1, postTitle: "Great post", commentIds: [2] }
1009
+ ],
1010
+ comments: [
1011
+ { id: 2, commentBody: "Insightful comment" }
1012
+ ]
1013
+ }
1014
+
1015
+ store.pushPayload(pushData);
1016
+ ```
1017
+
1018
+ By default, the data will be deserialized using a default
1019
+ serializer (the application serializer if it exists).
1020
+
1021
+ Alternatively, `pushPayload` will accept a model type which
1022
+ will determine which serializer will process the payload.
1023
+
1024
+ ```app/serializers/application.js
1025
+ import RESTSerializer from '@ember-data/serializer/rest';
1026
+
1027
+ export default class ApplicationSerializer extends RESTSerializer;
1028
+ ```
1029
+
1030
+ ```app/serializers/post.js
1031
+ import JSONSerializer from '@ember-data/serializer/json';
1032
+
1033
+ export default JSONSerializer;
1034
+ ```
1035
+
1036
+ ```js
1037
+ store.pushPayload(pushData); // Will use the application serializer
1038
+ store.pushPayload('post', pushData); // Will use the post serializer
1039
+ ```
1040
+
1041
+ @method pushPayload
1042
+ @public
1043
+ @param {String} modelName Optionally, a model type used to determine which serializer will be used
1044
+ @param {Object} inputPayload
1045
+ */
1046
+ // TODO @runspired @deprecate pushPayload in favor of looking up the serializer
1047
+ function pushPayload(modelName, inputPayload) {
1048
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1049
+ if (!test) {
1050
+ throw new Error(`Attempted to call store.pushPayload(), but the store instance has already been destroyed.`);
1051
+ }
1052
+ })(!(this.isDestroying || this.isDestroyed)) : {};
1053
+ const payload = inputPayload || modelName;
1054
+ const normalizedModelName = inputPayload ? normalizeModelName(modelName) : 'application';
1055
+ const serializer = this.serializerFor(normalizedModelName);
1056
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
1057
+ if (!test) {
1058
+ throw new Error(`You cannot use 'store.pushPayload(<type>, <payload>)' unless the serializer for '${normalizedModelName}' defines 'pushPayload'`);
1059
+ }
1060
+ })(serializer && typeof serializer.pushPayload === 'function') : {};
1061
+ serializer.pushPayload(this, payload);
1062
+ }
1063
+
1064
+ // TODO @runspired @deprecate records should implement their own serialization if desired
1065
+ function serializeRecord(record, options) {
1066
+ // TODO we used to check if the record was destroyed here
1067
+ if (!this._fetchManager) {
1068
+ this._fetchManager = new FetchManager(this);
1069
+ }
1070
+ return this._fetchManager.createSnapshot(recordIdentifierFor(record)).serialize(options);
1071
+ }
1072
+ function cleanup() {
1073
+ // enqueue destruction of any adapters/serializers we have created
1074
+ for (const adapterName in this._adapterCache) {
1075
+ const adapter = this._adapterCache[adapterName];
1076
+ if (typeof adapter.destroy === 'function') {
1077
+ adapter.destroy();
1078
+ }
1079
+ }
1080
+ for (const serializerName in this._serializerCache) {
1081
+ const serializer = this._serializerCache[serializerName];
1082
+ if (typeof serializer.destroy === 'function') {
1083
+ serializer.destroy();
1084
+ }
1085
+ }
1086
+ }
1087
+ export { LegacyNetworkHandler, adapterFor, cleanup, normalize, pushPayload, serializeRecord, serializerFor };