@ember-data/legacy-compat 5.5.0-alpha.2 → 5.5.0-alpha.21

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-0744e8e9.js → dist/-private-Dlia0pw1.js} +252 -125
  5. package/dist/-private-Dlia0pw1.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-0744e8e9.js.map +0 -1
  66. package/addon/index.js +0 -617
  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,617 +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-0744e8e9";
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
- /*
360
- // TODO @runspired re-evaluate the below claim now that
361
- // the save request pipeline is more streamlined.
362
- Note to future spelunkers hoping to optimize.
363
- We rely on this `run` to create a run loop if needed
364
- that `store._push` and `store.saveRecord` will both share.
365
- We use `join` because it is often the case that we
366
- have an outer run loop available still from the first
367
- call to `store._push`;
368
- */
369
- store._join(() => {
370
- result = store.cache.didCommit(identifier, {
371
- request: context.request,
372
- content: payload
373
- });
374
- });
375
- return store.peekRecord(result.data);
376
- }).catch(e => {
377
- let err = e;
378
- if (!e) {
379
- err = new Error(`Unknown Error Occurred During Request`);
380
- } else if (typeof e === 'string') {
381
- err = new Error(e);
382
- }
383
- adapterDidInvalidate(store, identifier, err);
384
- throw err;
385
- });
386
- }
387
- function adapterDidInvalidate(store, identifier, error) {
388
- if (error && error.isAdapterError === true && error.code === 'InvalidError') {
389
- let serializer = store.serializerFor(identifier.type);
390
-
391
- // TODO @deprecate extractErrors being called
392
- // TODO remove extractErrors from the default serializers.
393
- if (serializer && typeof serializer.extractErrors === 'function') {
394
- let errorsHash = serializer.extractErrors(store, store.modelFor(identifier.type), error, identifier.id);
395
- error.errors = errorsHashToArray(errorsHash);
396
- }
397
- }
398
- const cache = store.cache;
399
- if (error.errors) {
400
- assert(`Expected the cache in use by resource ${String(identifier)} to have a getErrors(identifier) method for retreiving errors.`, typeof cache.getErrors === 'function');
401
- let jsonApiErrors = error.errors;
402
- if (jsonApiErrors.length === 0) {
403
- jsonApiErrors = [{
404
- title: 'Invalid Error',
405
- detail: '',
406
- source: {
407
- pointer: '/data'
408
- }
409
- }];
410
- }
411
- cache.commitWasRejected(identifier, jsonApiErrors);
412
- } else {
413
- cache.commitWasRejected(identifier);
414
- }
415
- }
416
- function makeArray(value) {
417
- return Array.isArray(value) ? value : [value];
418
- }
419
- const PRIMARY_ATTRIBUTE_KEY = 'base';
420
- function errorsHashToArray(errors) {
421
- const out = [];
422
- if (errors) {
423
- Object.keys(errors).forEach(key => {
424
- let messages = makeArray(errors[key]);
425
- for (let i = 0; i < messages.length; i++) {
426
- let title = 'Invalid Attribute';
427
- let pointer = `/data/attributes/${key}`;
428
- if (key === PRIMARY_ATTRIBUTE_KEY) {
429
- title = 'Invalid Document';
430
- pointer = `/data`;
431
- }
432
- out.push({
433
- title: title,
434
- detail: messages[i],
435
- source: {
436
- pointer: pointer
437
- }
438
- });
439
- }
440
- });
441
- }
442
- return out;
443
- }
444
- function findRecord(context) {
445
- const {
446
- store,
447
- data
448
- } = context.request;
449
- const {
450
- record: identifier,
451
- options
452
- } = data;
453
- let promise;
454
-
455
- // if not loaded start loading
456
- if (!store._instanceCache.recordIsLoaded(identifier)) {
457
- promise = store._fetchManager.fetchDataIfNeededForIdentifier(identifier, options, context.request);
458
-
459
- // Refetch if the reload option is passed
460
- } else if (options.reload) {
461
- assertIdentifierHasId(identifier);
462
- promise = store._fetchManager.scheduleFetch(identifier, options, context.request);
463
- } else {
464
- let snapshot = null;
465
- let adapter = store.adapterFor(identifier.type);
466
-
467
- // Refetch the record if the adapter thinks the record is stale
468
- if (typeof options.reload === 'undefined' && adapter.shouldReloadRecord && adapter.shouldReloadRecord(store, snapshot = store._fetchManager.createSnapshot(identifier, options))) {
469
- assertIdentifierHasId(identifier);
470
- if (macroCondition(getOwnConfig().env.DEBUG)) {
471
- promise = store._fetchManager.scheduleFetch(identifier, Object.assign({}, options, {
472
- reload: true
473
- }), context.request);
474
- } else {
475
- options.reload = true;
476
- promise = store._fetchManager.scheduleFetch(identifier, options, context.request);
477
- }
478
- } else {
479
- // Trigger the background refetch if backgroundReload option is passed
480
- if (options.backgroundReload !== false && (options.backgroundReload || !adapter.shouldBackgroundReloadRecord || adapter.shouldBackgroundReloadRecord(store, snapshot = snapshot || store._fetchManager.createSnapshot(identifier, options)))) {
481
- assertIdentifierHasId(identifier);
482
- if (macroCondition(getOwnConfig().env.DEBUG)) {
483
- void store._fetchManager.scheduleFetch(identifier, Object.assign({}, options, {
484
- backgroundReload: true
485
- }), context.request);
486
- } else {
487
- options.backgroundReload = true;
488
- void store._fetchManager.scheduleFetch(identifier, options, context.request);
489
- }
490
- }
491
-
492
- // Return the cached record
493
- promise = Promise.resolve(identifier);
494
- }
495
- }
496
- return promise.then(i => store.peekRecord(i));
497
- }
498
- function findAll(context) {
499
- const {
500
- store,
501
- data
502
- } = context.request;
503
- const {
504
- type,
505
- options
506
- } = data;
507
- const adapter = store.adapterFor(type);
508
- assert(`You tried to load all records but you have no adapter (for ${type})`, adapter);
509
- assert(`You tried to load all records but your adapter does not implement 'findAll'`, typeof adapter.findAll === 'function');
510
-
511
- // avoid initializing the liveArray just to set `isUpdating`
512
- const maybeRecordArray = store.recordArrayManager._live.get(type);
513
- const snapshotArray = new SnapshotRecordArray(store, type, options);
514
- const shouldReload = options.reload || options.reload !== false && (adapter.shouldReloadAll && adapter.shouldReloadAll(store, snapshotArray) || !adapter.shouldReloadAll && snapshotArray.length === 0);
515
- let fetch;
516
- if (shouldReload) {
517
- maybeRecordArray && (maybeRecordArray.isUpdating = true);
518
- fetch = _findAll(adapter, store, type, snapshotArray, context.request, true);
519
- } else {
520
- fetch = Promise.resolve(store.peekAll(type));
521
- if (options.backgroundReload || options.backgroundReload !== false && (!adapter.shouldBackgroundReloadAll || adapter.shouldBackgroundReloadAll(store, snapshotArray))) {
522
- maybeRecordArray && (maybeRecordArray.isUpdating = true);
523
- void _findAll(adapter, store, type, snapshotArray, context.request, false);
524
- }
525
- }
526
- return fetch;
527
- }
528
- function _findAll(adapter, store, type, snapshotArray, request, isAsyncFlush) {
529
- const schema = store.modelFor(type);
530
- let promise = Promise.resolve().then(() => adapter.findAll(store, schema, null, snapshotArray));
531
- promise = promise.then(adapterPayload => {
532
- assert(`You made a 'findAll' request for '${type}' records, but the adapter's response did not have any data`, payloadIsNotBlank(adapterPayload));
533
- const serializer = store.serializerFor(type);
534
- const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'findAll');
535
- store._push(payload, isAsyncFlush);
536
- snapshotArray._recordArray.isUpdating = false;
537
- if (macroCondition(getOwnConfig().debug.LOG_PAYLOADS)) {
538
- // eslint-disable-next-line no-console
539
- console.log(`request: findAll<${type}> background reload complete`);
540
- }
541
- return snapshotArray._recordArray;
542
- });
543
- if (macroCondition(getOwnConfig().env.TESTING)) {
544
- if (!request.disableTestWaiter) {
545
- const {
546
- waitForPromise
547
- } = importSync('@ember/test-waiters');
548
- promise = waitForPromise(promise);
549
- }
550
- }
551
- return promise;
552
- }
553
- function query(context) {
554
- const {
555
- store,
556
- data
557
- } = context.request;
558
- let {
559
- options
560
- } = data;
561
- // eslint-disable-next-line @typescript-eslint/no-shadow
562
- const {
563
- type,
564
- query
565
- } = data;
566
- const adapter = store.adapterFor(type);
567
- assert(`You tried to make a query but you have no adapter (for ${type})`, adapter);
568
- assert(`You tried to make a query but your adapter does not implement 'query'`, typeof adapter.query === 'function');
569
- const recordArray = options._recordArray || store.recordArrayManager.createArray({
570
- type,
571
- query
572
- });
573
- if (macroCondition(getOwnConfig().env.DEBUG)) {
574
- options = Object.assign({}, options);
575
- delete options._recordArray;
576
- } else {
577
- delete options._recordArray;
578
- }
579
- const schema = store.modelFor(type);
580
- let promise = Promise.resolve().then(() => adapter.query(store, schema, query, recordArray, options));
581
- return promise.then(adapterPayload => {
582
- const serializer = store.serializerFor(type);
583
- const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'query');
584
- const identifiers = store._push(payload, true);
585
- 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));
586
- store.recordArrayManager.populateManagedArray(recordArray, identifiers, payload);
587
- return recordArray;
588
- });
589
- }
590
- function assertSingleResourceDocument(payload) {
591
- 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));
592
- }
593
- function queryRecord(context) {
594
- const {
595
- store,
596
- data
597
- } = context.request;
598
- // eslint-disable-next-line @typescript-eslint/no-shadow
599
- const {
600
- type,
601
- query,
602
- options
603
- } = data;
604
- const adapter = store.adapterFor(type);
605
- assert(`You tried to make a query but you have no adapter (for ${type})`, adapter);
606
- assert(`You tried to make a query but your adapter does not implement 'queryRecord'`, typeof adapter.queryRecord === 'function');
607
- const schema = store.modelFor(type);
608
- let promise = Promise.resolve().then(() => adapter.queryRecord(store, schema, query, options));
609
- return promise.then(adapterPayload => {
610
- const serializer = store.serializerFor(type);
611
- const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'queryRecord');
612
- assertSingleResourceDocument(payload);
613
- const identifier = store._push(payload, true);
614
- return identifier ? store.peekRecord(identifier) : null;
615
- });
616
- }
617
- export { LegacyNetworkHandler };