@ember-data/legacy-compat 5.5.0-alpha.9 → 5.5.0

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 (71) hide show
  1. package/LICENSE.md +19 -7
  2. package/README.md +10 -2
  3. package/addon-main.cjs +5 -0
  4. package/{addon/fetch-manager-d705ddaf.js → dist/-private-Bnt-3W7M.js} +253 -126
  5. package/dist/-private-Bnt-3W7M.js.map +1 -0
  6. package/dist/-private.js +1 -0
  7. package/dist/builders.js +323 -0
  8. package/dist/builders.js.map +1 -0
  9. package/dist/index.js +1011 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/utils.js +246 -0
  12. package/dist/utils.js.map +1 -0
  13. package/logos/NCC-1701-a-blue.svg +4 -0
  14. package/logos/NCC-1701-a-gold.svg +4 -0
  15. package/logos/NCC-1701-a-gold_100.svg +1 -0
  16. package/logos/NCC-1701-a-gold_base-64.txt +1 -0
  17. package/logos/NCC-1701-a.svg +4 -0
  18. package/logos/README.md +4 -0
  19. package/logos/docs-badge.svg +2 -0
  20. package/logos/github-header.svg +444 -0
  21. package/logos/social1.png +0 -0
  22. package/logos/social2.png +0 -0
  23. package/logos/warp-drive-logo-dark.svg +4 -0
  24. package/logos/warp-drive-logo-gold.svg +4 -0
  25. package/package.json +58 -49
  26. package/unstable-preview-types/-private.d.ts +17 -0
  27. package/unstable-preview-types/-private.d.ts.map +1 -0
  28. package/unstable-preview-types/builders/find-all.d.ts +41 -0
  29. package/unstable-preview-types/builders/find-all.d.ts.map +1 -0
  30. package/unstable-preview-types/builders/find-record.d.ts +62 -0
  31. package/unstable-preview-types/builders/find-record.d.ts.map +1 -0
  32. package/unstable-preview-types/builders/query.d.ts +72 -0
  33. package/unstable-preview-types/builders/query.d.ts.map +1 -0
  34. package/unstable-preview-types/builders/save-record.d.ts +40 -0
  35. package/unstable-preview-types/builders/save-record.d.ts.map +1 -0
  36. package/unstable-preview-types/builders/utils.d.ts +6 -0
  37. package/unstable-preview-types/builders/utils.d.ts.map +1 -0
  38. package/unstable-preview-types/builders.d.ts +18 -0
  39. package/unstable-preview-types/builders.d.ts.map +1 -0
  40. package/unstable-preview-types/index.d.ts +162 -0
  41. package/unstable-preview-types/index.d.ts.map +1 -0
  42. package/unstable-preview-types/legacy-network-handler/fetch-manager.d.ts +49 -0
  43. package/unstable-preview-types/legacy-network-handler/fetch-manager.d.ts.map +1 -0
  44. package/unstable-preview-types/legacy-network-handler/identifier-has-id.d.ts +5 -0
  45. package/unstable-preview-types/legacy-network-handler/identifier-has-id.d.ts.map +1 -0
  46. package/unstable-preview-types/legacy-network-handler/legacy-data-fetch.d.ts +14 -0
  47. package/unstable-preview-types/legacy-network-handler/legacy-data-fetch.d.ts.map +1 -0
  48. package/unstable-preview-types/legacy-network-handler/legacy-data-utils.d.ts +8 -0
  49. package/unstable-preview-types/legacy-network-handler/legacy-data-utils.d.ts.map +1 -0
  50. package/unstable-preview-types/legacy-network-handler/legacy-network-handler.d.ts +5 -0
  51. package/unstable-preview-types/legacy-network-handler/legacy-network-handler.d.ts.map +1 -0
  52. package/unstable-preview-types/legacy-network-handler/minimum-adapter-interface.d.ts +549 -0
  53. package/unstable-preview-types/legacy-network-handler/minimum-adapter-interface.d.ts.map +1 -0
  54. package/unstable-preview-types/legacy-network-handler/minimum-serializer-interface.d.ts +235 -0
  55. package/unstable-preview-types/legacy-network-handler/minimum-serializer-interface.d.ts.map +1 -0
  56. package/unstable-preview-types/legacy-network-handler/serializer-response.d.ts +9 -0
  57. package/unstable-preview-types/legacy-network-handler/serializer-response.d.ts.map +1 -0
  58. package/unstable-preview-types/legacy-network-handler/snapshot-record-array.d.ts +96 -0
  59. package/unstable-preview-types/legacy-network-handler/snapshot-record-array.d.ts.map +1 -0
  60. package/unstable-preview-types/legacy-network-handler/snapshot.d.ts +248 -0
  61. package/unstable-preview-types/legacy-network-handler/snapshot.d.ts.map +1 -0
  62. package/unstable-preview-types/utils.d.ts +161 -0
  63. package/unstable-preview-types/utils.d.ts.map +1 -0
  64. package/addon/-private.js +0 -1
  65. package/addon/fetch-manager-d705ddaf.js.map +0 -1
  66. package/addon/index.js +0 -608
  67. package/addon/index.js.map +0 -1
  68. package/addon-main.js +0 -93
  69. /package/{addon → dist}/-private.js.map +0 -0
  70. /package/{ember-data-logo-dark.svg → logos/ember-data-logo-dark.svg} +0 -0
  71. /package/{ember-data-logo-light.svg → logos/ember-data-logo-light.svg} +0 -0
package/addon/index.js DELETED
@@ -1,608 +0,0 @@
1
- import { assert } from '@ember/debug';
2
- import { macroCondition, getOwnConfig, importSync } from '@embroider/macros';
3
- import { p as payloadIsNotBlank, n as normalizeResponseHelper, i as iterateData, F as FetchManager, c as assertIdentifierHasId, a as SaveOp, S as SnapshotRecordArray } from "./fetch-manager-d705ddaf";
4
- function _findHasMany(adapter, store, identifier, link, relationship, options) {
5
- let promise = Promise.resolve().then(() => {
6
- const snapshot = store._fetchManager.createSnapshot(identifier, options);
7
- let useLink = !link || typeof link === 'string';
8
- let relatedLink = useLink ? link : link.href;
9
- return adapter.findHasMany(store, snapshot, relatedLink, relationship);
10
- });
11
- promise = promise.then(adapterPayload => {
12
- assert(`You made a 'findHasMany' request for a ${identifier.type}'s '${relationship.key}' relationship, using link '${link}' , but the adapter's response did not have any data`, payloadIsNotBlank(adapterPayload));
13
- const modelClass = store.modelFor(relationship.type);
14
- let serializer = store.serializerFor(relationship.type);
15
- let payload = normalizeResponseHelper(serializer, store, modelClass, adapterPayload, null, 'findHasMany');
16
- assert(`fetched the hasMany relationship '${relationship.name}' for ${identifier.type}:${identifier.id} with link '${link}', but no data member is present in the response. If no data exists, the response should set { data: [] }`, 'data' in payload && Array.isArray(payload.data));
17
- payload = syncRelationshipDataFromLink(store, payload, identifier, relationship);
18
- return store._push(payload, true);
19
- }, null, `DS: Extract payload of '${identifier.type}' : hasMany '${relationship.type}'`);
20
- return promise;
21
- }
22
- function _findBelongsTo(store, identifier, link, relationship, options) {
23
- let promise = Promise.resolve().then(() => {
24
- let adapter = store.adapterFor(identifier.type);
25
- assert(`You tried to load a belongsTo relationship but you have no adapter (for ${identifier.type})`, adapter);
26
- assert(`You tried to load a belongsTo relationship from a specified 'link' in the original payload but your adapter does not implement 'findBelongsTo'`, typeof adapter.findBelongsTo === 'function');
27
- let snapshot = store._fetchManager.createSnapshot(identifier, options);
28
- let useLink = !link || typeof link === 'string';
29
- let relatedLink = useLink ? link : link.href;
30
- return adapter.findBelongsTo(store, snapshot, relatedLink, relationship);
31
- });
32
- promise = promise.then(adapterPayload => {
33
- let modelClass = store.modelFor(relationship.type);
34
- let serializer = store.serializerFor(relationship.type);
35
- let payload = normalizeResponseHelper(serializer, store, modelClass, adapterPayload, null, 'findBelongsTo');
36
- assert(`fetched the belongsTo relationship '${relationship.name}' for ${identifier.type}:${identifier.id} with link '${link}', but no data member is present in the response. If no data exists, the response should set { data: null }`, 'data' in payload && (payload.data === null || typeof payload.data === 'object' && !Array.isArray(payload.data)));
37
- if (!payload.data && !payload.links && !payload.meta) {
38
- return null;
39
- }
40
- payload = syncRelationshipDataFromLink(store, payload, identifier, relationship);
41
- return store._push(payload, true);
42
- }, null, `DS: Extract payload of ${identifier.type} : ${relationship.type}`);
43
- return promise;
44
- }
45
-
46
- // sync
47
- // iterate over records in payload.data
48
- // for each record
49
- // assert that record.relationships[inverse] is either undefined (so we can fix it)
50
- // or provide a data: {id, type} that matches the record that requested it
51
- // return the relationship data for the parent
52
- function syncRelationshipDataFromLink(store, payload, parentIdentifier, relationship) {
53
- // ensure the right hand side (incoming payload) points to the parent record that
54
- // requested this relationship
55
- let relationshipData = payload.data ? iterateData(payload.data, (data, index) => {
56
- const {
57
- id,
58
- type
59
- } = data;
60
- ensureRelationshipIsSetToParent(data, parentIdentifier, store, relationship, index);
61
- return {
62
- id,
63
- type
64
- };
65
- }) : null;
66
- const relatedDataHash = {};
67
- if ('meta' in payload) {
68
- relatedDataHash.meta = payload.meta;
69
- }
70
- if ('links' in payload) {
71
- relatedDataHash.links = payload.links;
72
- }
73
- if ('data' in payload) {
74
- relatedDataHash.data = relationshipData;
75
- }
76
-
77
- // now, push the left hand side (the parent record) to ensure things are in sync, since
78
- // the payload will be pushed with store._push
79
- const parentPayload = {
80
- id: parentIdentifier.id,
81
- type: parentIdentifier.type,
82
- relationships: {
83
- [relationship.key]: relatedDataHash
84
- }
85
- };
86
- if (!Array.isArray(payload.included)) {
87
- payload.included = [];
88
- }
89
- payload.included.push(parentPayload);
90
- return payload;
91
- }
92
- function ensureRelationshipIsSetToParent(payload, parentIdentifier, store, parentRelationship, index) {
93
- let {
94
- id,
95
- type
96
- } = payload;
97
- if (!payload.relationships) {
98
- payload.relationships = {};
99
- }
100
- let {
101
- relationships
102
- } = payload;
103
- let inverse = getInverse(store, parentIdentifier, parentRelationship, type);
104
- if (inverse) {
105
- let {
106
- inverseKey,
107
- kind
108
- } = inverse;
109
- let relationshipData = relationships[inverseKey] && relationships[inverseKey].data;
110
- if (macroCondition(getOwnConfig().env.DEBUG)) {
111
- if (typeof relationshipData !== 'undefined' && !relationshipDataPointsToParent(relationshipData, parentIdentifier)) {
112
- let inspect = function inspect(thing) {
113
- return `'${JSON.stringify(thing)}'`;
114
- };
115
- let quotedType = inspect(type);
116
- let quotedInverse = inspect(inverseKey);
117
- let expected = inspect({
118
- id: parentIdentifier.id,
119
- type: parentIdentifier.type
120
- });
121
- let expectedModel = `${parentIdentifier.type}:${parentIdentifier.id}`;
122
- let got = inspect(relationshipData);
123
- let prefix = typeof index === 'number' ? `data[${index}]` : `data`;
124
- let path = `${prefix}.relationships.${inverseKey}.data`;
125
- let other = relationshipData ? `<${relationshipData.type}:${relationshipData.id}>` : null;
126
- let relationshipFetched = `${expectedModel}.${parentRelationship.kind}("${parentRelationship.name}")`;
127
- let includedRecord = `<${type}:${id}>`;
128
- let 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');
129
- assert(message);
130
- }
131
- }
132
- if (kind !== 'hasMany' || typeof relationshipData !== 'undefined') {
133
- relationships[inverseKey] = relationships[inverseKey] || {};
134
- relationships[inverseKey].data = fixRelationshipData(relationshipData, kind, parentIdentifier);
135
- }
136
- }
137
- }
138
- function inverseForRelationship(store, identifier, key) {
139
- const definition = store.getSchemaDefinitionService().relationshipsDefinitionFor(identifier)[key];
140
- if (!definition) {
141
- return null;
142
- }
143
- assert(`Expected the relationship defintion to specify the inverse type or null.`, definition.options?.inverse === null || typeof definition.options?.inverse === 'string' && definition.options.inverse.length > 0);
144
- return definition.options.inverse;
145
- }
146
- function getInverse(store, parentIdentifier, parentRelationship, type) {
147
- let {
148
- name: lhs_relationshipName
149
- } = parentRelationship;
150
- let {
151
- type: parentType
152
- } = parentIdentifier;
153
- let inverseKey = inverseForRelationship(store, {
154
- type: parentType
155
- }, lhs_relationshipName);
156
- if (inverseKey) {
157
- const definition = store.getSchemaDefinitionService().relationshipsDefinitionFor({
158
- type
159
- });
160
- let {
161
- kind
162
- } = definition[inverseKey];
163
- return {
164
- inverseKey,
165
- kind
166
- };
167
- }
168
- }
169
- function relationshipDataPointsToParent(relationshipData, identifier) {
170
- if (relationshipData === null) {
171
- return false;
172
- }
173
- if (Array.isArray(relationshipData)) {
174
- if (relationshipData.length === 0) {
175
- return false;
176
- }
177
- for (let i = 0; i < relationshipData.length; i++) {
178
- let entry = relationshipData[i];
179
- if (validateRelationshipEntry(entry, identifier)) {
180
- return true;
181
- }
182
- }
183
- } else {
184
- return validateRelationshipEntry(relationshipData, identifier);
185
- }
186
- return false;
187
- }
188
- function fixRelationshipData(relationshipData, relationshipKind, {
189
- id,
190
- type
191
- }) {
192
- let parentRelationshipData = {
193
- id,
194
- type
195
- };
196
- let payload;
197
- if (relationshipKind === 'hasMany') {
198
- payload = relationshipData || [];
199
- if (relationshipData) {
200
- // these arrays could be massive so this is better than filter
201
- // Note: this is potentially problematic if type/id are not in the
202
- // same state of normalization.
203
- let found = relationshipData.find(v => {
204
- return v.type === parentRelationshipData.type && v.id === parentRelationshipData.id;
205
- });
206
- if (!found) {
207
- payload.push(parentRelationshipData);
208
- }
209
- } else {
210
- payload.push(parentRelationshipData);
211
- }
212
- } else {
213
- payload = relationshipData || {};
214
- Object.assign(payload, parentRelationshipData);
215
- }
216
- return payload;
217
- }
218
- function validateRelationshipEntry({
219
- id
220
- }, {
221
- id: parentModelID
222
- }) {
223
- return id && id.toString() === parentModelID;
224
- }
225
- const PotentialLegacyOperations = new Set(['findRecord', 'findAll', 'query', 'queryRecord', 'findBelongsTo', 'findHasMany', 'updateRecord', 'createRecord', 'deleteRecord']);
226
- const LegacyNetworkHandler = {
227
- request(context, next) {
228
- // if we are not a legacy request, move on
229
- if (context.request.url || !context.request.op || !PotentialLegacyOperations.has(context.request.op)) {
230
- return next(context.request);
231
- }
232
- const {
233
- store
234
- } = context.request;
235
- if (!store._fetchManager) {
236
- store._fetchManager = new FetchManager(store);
237
- }
238
- switch (context.request.op) {
239
- case 'findRecord':
240
- return findRecord(context);
241
- case 'findAll':
242
- return findAll(context);
243
- case 'query':
244
- return query(context);
245
- case 'queryRecord':
246
- return queryRecord(context);
247
- case 'findBelongsTo':
248
- return findBelongsTo(context);
249
- case 'findHasMany':
250
- return findHasMany(context);
251
- case 'updateRecord':
252
- return saveRecord(context);
253
- case 'createRecord':
254
- return saveRecord(context);
255
- case 'deleteRecord':
256
- return saveRecord(context);
257
- default:
258
- return next(context.request);
259
- }
260
- }
261
- };
262
- function findBelongsTo(context) {
263
- const {
264
- store,
265
- data,
266
- records: identifiers
267
- } = context.request;
268
- const {
269
- options,
270
- record,
271
- links,
272
- useLink,
273
- field
274
- } = data;
275
- const identifier = identifiers?.[0];
276
-
277
- // short circuit if we are already loading
278
- let pendingRequest = identifier && store._fetchManager.getPendingFetch(identifier, options);
279
- if (pendingRequest) {
280
- return pendingRequest;
281
- }
282
- if (useLink) {
283
- return _findBelongsTo(store, record, links.related, field, options);
284
- }
285
- assert(`Expected an identifier`, Array.isArray(identifiers) && identifiers.length === 1);
286
- const manager = store._fetchManager;
287
- assertIdentifierHasId(identifier);
288
- return options.reload ? manager.scheduleFetch(identifier, options, context.request) : manager.fetchDataIfNeededForIdentifier(identifier, options, context.request);
289
- }
290
- function findHasMany(context) {
291
- const {
292
- store,
293
- data,
294
- records: identifiers
295
- } = context.request;
296
- const {
297
- options,
298
- record,
299
- links,
300
- useLink,
301
- field
302
- } = data;
303
-
304
- // link case
305
- if (useLink) {
306
- const adapter = store.adapterFor(record.type);
307
- /*
308
- If a relationship was originally populated by the adapter as a link
309
- (as opposed to a list of IDs), this method is called when the
310
- relationship is fetched.
311
- The link (which is usually a URL) is passed through unchanged, so the
312
- adapter can make whatever request it wants.
313
- The usual use-case is for the server to register a URL as a link, and
314
- then use that URL in the future to make a request for the relationship.
315
- */
316
- assert(`You tried to load a hasMany relationship but you have no adapter (for ${record.type})`, adapter);
317
- assert(`You tried to load a hasMany relationship from a specified 'link' in the original payload but your adapter does not implement 'findHasMany'`, typeof adapter.findHasMany === 'function');
318
- return _findHasMany(adapter, store, record, links.related, field, options);
319
- }
320
-
321
- // identifiers case
322
-
323
- const fetches = new Array(identifiers.length);
324
- const manager = store._fetchManager;
325
- for (let i = 0; i < identifiers.length; i++) {
326
- let identifier = identifiers[i];
327
- // TODO we probably can be lenient here and return from cache for the isNew case
328
- assertIdentifierHasId(identifier);
329
- fetches[i] = options.reload ? manager.scheduleFetch(identifier, options, context.request) : manager.fetchDataIfNeededForIdentifier(identifier, options, context.request);
330
- }
331
- return Promise.all(fetches);
332
- }
333
- function saveRecord(context) {
334
- const {
335
- store,
336
- data,
337
- op: operation
338
- } = context.request;
339
- const {
340
- options,
341
- record: identifier
342
- } = data;
343
- const saveOptions = Object.assign({
344
- [SaveOp]: operation
345
- }, options);
346
- const fetchManagerPromise = store._fetchManager.scheduleSave(identifier, saveOptions);
347
- return fetchManagerPromise.then(payload => {
348
- if (macroCondition(getOwnConfig().debug.LOG_PAYLOADS)) {
349
- try {
350
- let payloadCopy = payload ? JSON.parse(JSON.stringify(payload)) : payload;
351
- // eslint-disable-next-line no-console
352
- console.log(`EmberData | Payload - ${operation}`, payloadCopy);
353
- } catch (e) {
354
- // eslint-disable-next-line no-console
355
- console.log(`EmberData | Payload - ${operation}`, payload);
356
- }
357
- }
358
- let result;
359
- store._join(() => {
360
- // @ts-expect-error we don't have access to a response in legacy
361
- result = store.cache.didCommit(identifier, {
362
- request: context.request,
363
- content: payload
364
- });
365
- });
366
- return store.peekRecord(result.data);
367
- }).catch(e => {
368
- let err = e;
369
- if (!e) {
370
- err = new Error(`Unknown Error Occurred During Request`);
371
- } else if (typeof e === 'string') {
372
- err = new Error(e);
373
- }
374
- adapterDidInvalidate(store, identifier, err);
375
- throw err;
376
- });
377
- }
378
- function adapterDidInvalidate(store, identifier, error) {
379
- if (error && error.isAdapterError === true && error.code === 'InvalidError') {
380
- let serializer = store.serializerFor(identifier.type);
381
-
382
- // TODO @deprecate extractErrors being called
383
- // TODO remove extractErrors from the default serializers.
384
- if (serializer && typeof serializer.extractErrors === 'function') {
385
- let errorsHash = serializer.extractErrors(store, store.modelFor(identifier.type), error, identifier.id);
386
- error.errors = errorsHashToArray(errorsHash);
387
- }
388
- }
389
- const cache = store.cache;
390
- if (error.errors) {
391
- assert(`Expected the cache in use by resource ${String(identifier)} to have a getErrors(identifier) method for retreiving errors.`, typeof cache.getErrors === 'function');
392
- let jsonApiErrors = error.errors;
393
- if (jsonApiErrors.length === 0) {
394
- jsonApiErrors = [{
395
- title: 'Invalid Error',
396
- detail: '',
397
- source: {
398
- pointer: '/data'
399
- }
400
- }];
401
- }
402
- cache.commitWasRejected(identifier, jsonApiErrors);
403
- } else {
404
- cache.commitWasRejected(identifier);
405
- }
406
- }
407
- function makeArray(value) {
408
- return Array.isArray(value) ? value : [value];
409
- }
410
- const PRIMARY_ATTRIBUTE_KEY = 'base';
411
- function errorsHashToArray(errors) {
412
- const out = [];
413
- if (errors) {
414
- Object.keys(errors).forEach(key => {
415
- let messages = makeArray(errors[key]);
416
- for (let i = 0; i < messages.length; i++) {
417
- let title = 'Invalid Attribute';
418
- let pointer = `/data/attributes/${key}`;
419
- if (key === PRIMARY_ATTRIBUTE_KEY) {
420
- title = 'Invalid Document';
421
- pointer = `/data`;
422
- }
423
- out.push({
424
- title: title,
425
- detail: messages[i],
426
- source: {
427
- pointer: pointer
428
- }
429
- });
430
- }
431
- });
432
- }
433
- return out;
434
- }
435
- function findRecord(context) {
436
- const {
437
- store,
438
- data
439
- } = context.request;
440
- const {
441
- record: identifier,
442
- options
443
- } = data;
444
- let promise;
445
-
446
- // if not loaded start loading
447
- if (!store._instanceCache.recordIsLoaded(identifier)) {
448
- promise = store._fetchManager.fetchDataIfNeededForIdentifier(identifier, options, context.request);
449
-
450
- // Refetch if the reload option is passed
451
- } else if (options.reload) {
452
- assertIdentifierHasId(identifier);
453
- promise = store._fetchManager.scheduleFetch(identifier, options, context.request);
454
- } else {
455
- let snapshot = null;
456
- let adapter = store.adapterFor(identifier.type);
457
-
458
- // Refetch the record if the adapter thinks the record is stale
459
- if (typeof options.reload === 'undefined' && adapter.shouldReloadRecord && adapter.shouldReloadRecord(store, snapshot = store._fetchManager.createSnapshot(identifier, options))) {
460
- assertIdentifierHasId(identifier);
461
- if (macroCondition(getOwnConfig().env.DEBUG)) {
462
- promise = store._fetchManager.scheduleFetch(identifier, Object.assign({}, options, {
463
- reload: true
464
- }), context.request);
465
- } else {
466
- options.reload = true;
467
- promise = store._fetchManager.scheduleFetch(identifier, options, context.request);
468
- }
469
- } else {
470
- // Trigger the background refetch if backgroundReload option is passed
471
- if (options.backgroundReload !== false && (options.backgroundReload || !adapter.shouldBackgroundReloadRecord || adapter.shouldBackgroundReloadRecord(store, snapshot = snapshot || store._fetchManager.createSnapshot(identifier, options)))) {
472
- assertIdentifierHasId(identifier);
473
- if (macroCondition(getOwnConfig().env.DEBUG)) {
474
- void store._fetchManager.scheduleFetch(identifier, Object.assign({}, options, {
475
- backgroundReload: true
476
- }), context.request);
477
- } else {
478
- options.backgroundReload = true;
479
- void store._fetchManager.scheduleFetch(identifier, options, context.request);
480
- }
481
- }
482
-
483
- // Return the cached record
484
- promise = Promise.resolve(identifier);
485
- }
486
- }
487
- return promise.then(i => store.peekRecord(i));
488
- }
489
- function findAll(context) {
490
- const {
491
- store,
492
- data
493
- } = context.request;
494
- const {
495
- type,
496
- options
497
- } = data;
498
- const adapter = store.adapterFor(type);
499
- assert(`You tried to load all records but you have no adapter (for ${type})`, adapter);
500
- assert(`You tried to load all records but your adapter does not implement 'findAll'`, typeof adapter.findAll === 'function');
501
-
502
- // avoid initializing the liveArray just to set `isUpdating`
503
- const maybeRecordArray = store.recordArrayManager._live.get(type);
504
- const snapshotArray = new SnapshotRecordArray(store, type, options);
505
- const shouldReload = options.reload || options.reload !== false && (adapter.shouldReloadAll && adapter.shouldReloadAll(store, snapshotArray) || !adapter.shouldReloadAll && snapshotArray.length === 0);
506
- let fetch;
507
- if (shouldReload) {
508
- maybeRecordArray && (maybeRecordArray.isUpdating = true);
509
- fetch = _findAll(adapter, store, type, snapshotArray, context.request, true);
510
- } else {
511
- fetch = Promise.resolve(store.peekAll(type));
512
- if (options.backgroundReload || options.backgroundReload !== false && (!adapter.shouldBackgroundReloadAll || adapter.shouldBackgroundReloadAll(store, snapshotArray))) {
513
- maybeRecordArray && (maybeRecordArray.isUpdating = true);
514
- void _findAll(adapter, store, type, snapshotArray, context.request, false);
515
- }
516
- }
517
- return fetch;
518
- }
519
- function _findAll(adapter, store, type, snapshotArray, request, isAsyncFlush) {
520
- const schema = store.modelFor(type);
521
- let promise = Promise.resolve().then(() => adapter.findAll(store, schema, null, snapshotArray));
522
- promise = promise.then(adapterPayload => {
523
- assert(`You made a 'findAll' request for '${type}' records, but the adapter's response did not have any data`, payloadIsNotBlank(adapterPayload));
524
- const serializer = store.serializerFor(type);
525
- const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'findAll');
526
- store._push(payload, isAsyncFlush);
527
- snapshotArray._recordArray.isUpdating = false;
528
- if (macroCondition(getOwnConfig().debug.LOG_PAYLOADS)) {
529
- // eslint-disable-next-line no-console
530
- console.log(`request: findAll<${type}> background reload complete`);
531
- }
532
- return snapshotArray._recordArray;
533
- });
534
- if (macroCondition(getOwnConfig().env.TESTING)) {
535
- if (!request.disableTestWaiter) {
536
- const {
537
- waitForPromise
538
- } = importSync('@ember/test-waiters');
539
- promise = waitForPromise(promise);
540
- }
541
- }
542
- return promise;
543
- }
544
- function query(context) {
545
- const {
546
- store,
547
- data
548
- } = context.request;
549
- let {
550
- options
551
- } = data;
552
- // eslint-disable-next-line @typescript-eslint/no-shadow
553
- const {
554
- type,
555
- query
556
- } = data;
557
- const adapter = store.adapterFor(type);
558
- assert(`You tried to make a query but you have no adapter (for ${type})`, adapter);
559
- assert(`You tried to make a query but your adapter does not implement 'query'`, typeof adapter.query === 'function');
560
- const recordArray = options._recordArray || store.recordArrayManager.createArray({
561
- type,
562
- query
563
- });
564
- if (macroCondition(getOwnConfig().env.DEBUG)) {
565
- options = Object.assign({}, options);
566
- delete options._recordArray;
567
- } else {
568
- delete options._recordArray;
569
- }
570
- const schema = store.modelFor(type);
571
- let promise = Promise.resolve().then(() => adapter.query(store, schema, query, recordArray, options));
572
- return promise.then(adapterPayload => {
573
- const serializer = store.serializerFor(type);
574
- const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'query');
575
- const identifiers = store._push(payload, true);
576
- assert('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.', Array.isArray(identifiers));
577
- store.recordArrayManager.populateManagedArray(recordArray, identifiers, payload);
578
- return recordArray;
579
- });
580
- }
581
- function assertSingleResourceDocument(payload) {
582
- assert(`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.`, !Array.isArray(payload.data));
583
- }
584
- function queryRecord(context) {
585
- const {
586
- store,
587
- data
588
- } = context.request;
589
- // eslint-disable-next-line @typescript-eslint/no-shadow
590
- const {
591
- type,
592
- query,
593
- options
594
- } = data;
595
- const adapter = store.adapterFor(type);
596
- assert(`You tried to make a query but you have no adapter (for ${type})`, adapter);
597
- assert(`You tried to make a query but your adapter does not implement 'queryRecord'`, typeof adapter.queryRecord === 'function');
598
- const schema = store.modelFor(type);
599
- let promise = Promise.resolve().then(() => adapter.queryRecord(store, schema, query, options));
600
- return promise.then(adapterPayload => {
601
- const serializer = store.serializerFor(type);
602
- const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'queryRecord');
603
- assertSingleResourceDocument(payload);
604
- const identifier = store._push(payload, true);
605
- return identifier ? store.peekRecord(identifier) : null;
606
- });
607
- }
608
- export { LegacyNetworkHandler };