@ember-data/legacy-compat 5.4.0-alpha.4 → 5.4.0-alpha.41

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 (32) hide show
  1. package/addon/{fetch-manager-0744e8e9.js → -private-DmhhlB_x.js} +83 -70
  2. package/addon/-private-DmhhlB_x.js.map +1 -0
  3. package/addon/-private.js +1 -1
  4. package/addon/index.js +309 -76
  5. package/addon/index.js.map +1 -1
  6. package/addon-main.js +1 -0
  7. package/package.json +74 -28
  8. package/unstable-preview-types/-private.d.ts +17 -0
  9. package/unstable-preview-types/-private.d.ts.map +1 -0
  10. package/unstable-preview-types/index.d.ts +154 -0
  11. package/unstable-preview-types/index.d.ts.map +1 -0
  12. package/unstable-preview-types/legacy-network-handler/fetch-manager.d.ts +49 -0
  13. package/unstable-preview-types/legacy-network-handler/fetch-manager.d.ts.map +1 -0
  14. package/unstable-preview-types/legacy-network-handler/identifier-has-id.d.ts +5 -0
  15. package/unstable-preview-types/legacy-network-handler/identifier-has-id.d.ts.map +1 -0
  16. package/unstable-preview-types/legacy-network-handler/legacy-data-fetch.d.ts +14 -0
  17. package/unstable-preview-types/legacy-network-handler/legacy-data-fetch.d.ts.map +1 -0
  18. package/unstable-preview-types/legacy-network-handler/legacy-data-utils.d.ts +8 -0
  19. package/unstable-preview-types/legacy-network-handler/legacy-data-utils.d.ts.map +1 -0
  20. package/unstable-preview-types/legacy-network-handler/legacy-network-handler.d.ts +5 -0
  21. package/unstable-preview-types/legacy-network-handler/legacy-network-handler.d.ts.map +1 -0
  22. package/unstable-preview-types/legacy-network-handler/minimum-adapter-interface.d.ts +549 -0
  23. package/unstable-preview-types/legacy-network-handler/minimum-adapter-interface.d.ts.map +1 -0
  24. package/unstable-preview-types/legacy-network-handler/minimum-serializer-interface.d.ts +235 -0
  25. package/unstable-preview-types/legacy-network-handler/minimum-serializer-interface.d.ts.map +1 -0
  26. package/unstable-preview-types/legacy-network-handler/serializer-response.d.ts +9 -0
  27. package/unstable-preview-types/legacy-network-handler/serializer-response.d.ts.map +1 -0
  28. package/unstable-preview-types/legacy-network-handler/snapshot-record-array.d.ts +97 -0
  29. package/unstable-preview-types/legacy-network-handler/snapshot-record-array.d.ts.map +1 -0
  30. package/unstable-preview-types/legacy-network-handler/snapshot.d.ts +248 -0
  31. package/unstable-preview-types/legacy-network-handler/snapshot.d.ts.map +1 -0
  32. package/addon/fetch-manager-0744e8e9.js.map +0 -1
package/addon/index.js CHANGED
@@ -1,46 +1,50 @@
1
+ import { getOwner } from '@ember/application';
1
2
  import { assert } from '@ember/debug';
3
+ import { recordIdentifierFor } from '@ember-data/store';
4
+ import { _deprecatingNormalize } from '@ember-data/store/-private';
5
+ import { p as payloadIsNotBlank, n as normalizeResponseHelper, i as iterateData, F as FetchManager, a as assertIdentifierHasId, S as SaveOp, b as SnapshotRecordArray } from "./-private-DmhhlB_x";
2
6
  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
7
  function _findHasMany(adapter, store, identifier, link, relationship, options) {
5
- let promise = Promise.resolve().then(() => {
8
+ const promise = Promise.resolve().then(() => {
6
9
  const snapshot = store._fetchManager.createSnapshot(identifier, options);
7
- let useLink = !link || typeof link === 'string';
8
- let relatedLink = useLink ? link : link.href;
10
+ const useLink = !link || typeof link === 'string';
11
+ const relatedLink = useLink ? link : link.href;
12
+ assert(`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'`, relatedLink);
13
+ assert(`Expected the adapter to implement 'findHasMany' but it does not`, typeof adapter.findHasMany === 'function');
9
14
  return adapter.findHasMany(store, snapshot, relatedLink, relationship);
10
15
  });
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));
16
+ return promise.then(adapterPayload => {
17
+ assert(`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`, payloadIsNotBlank(adapterPayload));
13
18
  const modelClass = store.modelFor(relationship.type);
14
- let serializer = store.serializerFor(relationship.type);
19
+ const serializer = store.serializerFor(relationship.type);
15
20
  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));
21
+ assert(`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: [] }`, 'data' in payload && Array.isArray(payload.data));
17
22
  payload = syncRelationshipDataFromLink(store, payload, identifier, relationship);
18
23
  return store._push(payload, true);
19
- }, null, `DS: Extract payload of '${identifier.type}' : hasMany '${relationship.type}'`);
20
- return promise;
24
+ }, null);
21
25
  }
22
26
  function _findBelongsTo(store, identifier, link, relationship, options) {
23
- let promise = Promise.resolve().then(() => {
24
- let adapter = store.adapterFor(identifier.type);
27
+ const promise = Promise.resolve().then(() => {
28
+ const adapter = store.adapterFor(identifier.type);
25
29
  assert(`You tried to load a belongsTo relationship but you have no adapter (for ${identifier.type})`, adapter);
26
30
  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;
31
+ const snapshot = store._fetchManager.createSnapshot(identifier, options);
32
+ const useLink = !link || typeof link === 'string';
33
+ const relatedLink = useLink ? link : link.href;
34
+ assert(`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'`, relatedLink);
30
35
  return adapter.findBelongsTo(store, snapshot, relatedLink, relationship);
31
36
  });
32
- promise = promise.then(adapterPayload => {
33
- let modelClass = store.modelFor(relationship.type);
34
- let serializer = store.serializerFor(relationship.type);
37
+ return promise.then(adapterPayload => {
38
+ const modelClass = store.modelFor(relationship.type);
39
+ const serializer = store.serializerFor(relationship.type);
35
40
  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)));
41
+ assert(`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 }`, 'data' in payload && (payload.data === null || typeof payload.data === 'object' && !Array.isArray(payload.data)));
37
42
  if (!payload.data && !payload.links && !payload.meta) {
38
43
  return null;
39
44
  }
40
45
  payload = syncRelationshipDataFromLink(store, payload, identifier, relationship);
41
46
  return store._push(payload, true);
42
- }, null, `DS: Extract payload of ${identifier.type} : ${relationship.type}`);
43
- return promise;
47
+ }, null);
44
48
  }
45
49
 
46
50
  // sync
@@ -52,7 +56,7 @@ function _findBelongsTo(store, identifier, link, relationship, options) {
52
56
  function syncRelationshipDataFromLink(store, payload, parentIdentifier, relationship) {
53
57
  // ensure the right hand side (incoming payload) points to the parent record that
54
58
  // requested this relationship
55
- let relationshipData = payload.data ? iterateData(payload.data, (data, index) => {
59
+ const relationshipData = payload.data ? iterateData(payload.data, (data, index) => {
56
60
  const {
57
61
  id,
58
62
  type
@@ -80,7 +84,7 @@ function syncRelationshipDataFromLink(store, payload, parentIdentifier, relation
80
84
  id: parentIdentifier.id,
81
85
  type: parentIdentifier.type,
82
86
  relationships: {
83
- [relationship.key]: relatedDataHash
87
+ [relationship.name]: relatedDataHash
84
88
  }
85
89
  };
86
90
  if (!Array.isArray(payload.included)) {
@@ -90,48 +94,49 @@ function syncRelationshipDataFromLink(store, payload, parentIdentifier, relation
90
94
  return payload;
91
95
  }
92
96
  function ensureRelationshipIsSetToParent(payload, parentIdentifier, store, parentRelationship, index) {
93
- let {
97
+ const {
94
98
  id,
95
99
  type
96
100
  } = payload;
97
101
  if (!payload.relationships) {
98
102
  payload.relationships = {};
99
103
  }
100
- let {
104
+ const {
101
105
  relationships
102
106
  } = payload;
103
- let inverse = getInverse(store, parentIdentifier, parentRelationship, type);
107
+ const inverse = getInverse(store, parentIdentifier, parentRelationship, type);
104
108
  if (inverse) {
105
- let {
109
+ const {
106
110
  inverseKey,
107
111
  kind
108
112
  } = inverse;
109
- let relationshipData = relationships[inverseKey] && relationships[inverseKey].data;
113
+ const relationshipData = relationships[inverseKey]?.data;
110
114
  if (macroCondition(getOwnConfig().env.DEBUG)) {
111
115
  if (typeof relationshipData !== 'undefined' && !relationshipDataPointsToParent(relationshipData, parentIdentifier)) {
112
- let inspect = function inspect(thing) {
116
+ const inspect = function inspect(thing) {
113
117
  return `'${JSON.stringify(thing)}'`;
114
118
  };
115
- let quotedType = inspect(type);
116
- let quotedInverse = inspect(inverseKey);
117
- let expected = inspect({
119
+ const quotedType = inspect(type);
120
+ const quotedInverse = inspect(inverseKey);
121
+ const expected = inspect({
118
122
  id: parentIdentifier.id,
119
123
  type: parentIdentifier.type
120
124
  });
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');
125
+ const expectedModel = `${parentIdentifier.type}:${parentIdentifier.id}`;
126
+ const got = inspect(relationshipData);
127
+ const prefix = typeof index === 'number' ? `data[${index}]` : `data`;
128
+ const path = `${prefix}.relationships.${inverseKey}.data`;
129
+ const data = Array.isArray(relationshipData) ? relationshipData[0] : relationshipData;
130
+ const other = data ? `<${data.type}:${data.id}>` : null;
131
+ const relationshipFetched = `${expectedModel}.${parentRelationship.kind}("${parentRelationship.name}")`;
132
+ const includedRecord = `<${type}:${id}>`;
133
+ 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');
129
134
  assert(message);
130
135
  }
131
136
  }
132
137
  if (kind !== 'hasMany' || typeof relationshipData !== 'undefined') {
133
138
  relationships[inverseKey] = relationships[inverseKey] || {};
134
- relationships[inverseKey].data = fixRelationshipData(relationshipData, kind, parentIdentifier);
139
+ relationships[inverseKey].data = fixRelationshipData(relationshipData ?? null, kind, parentIdentifier);
135
140
  }
136
141
  }
137
142
  }
@@ -144,20 +149,20 @@ function inverseForRelationship(store, identifier, key) {
144
149
  return definition.options.inverse;
145
150
  }
146
151
  function getInverse(store, parentIdentifier, parentRelationship, type) {
147
- let {
152
+ const {
148
153
  name: lhs_relationshipName
149
154
  } = parentRelationship;
150
- let {
155
+ const {
151
156
  type: parentType
152
157
  } = parentIdentifier;
153
- let inverseKey = inverseForRelationship(store, {
158
+ const inverseKey = inverseForRelationship(store, {
154
159
  type: parentType
155
160
  }, lhs_relationshipName);
156
161
  if (inverseKey) {
157
162
  const definition = store.getSchemaDefinitionService().relationshipsDefinitionFor({
158
163
  type
159
164
  });
160
- let {
165
+ const {
161
166
  kind
162
167
  } = definition[inverseKey];
163
168
  return {
@@ -175,7 +180,7 @@ function relationshipDataPointsToParent(relationshipData, identifier) {
175
180
  return false;
176
181
  }
177
182
  for (let i = 0; i < relationshipData.length; i++) {
178
- let entry = relationshipData[i];
183
+ const entry = relationshipData[i];
179
184
  if (validateRelationshipEntry(entry, identifier)) {
180
185
  return true;
181
186
  }
@@ -189,29 +194,32 @@ function fixRelationshipData(relationshipData, relationshipKind, {
189
194
  id,
190
195
  type
191
196
  }) {
192
- let parentRelationshipData = {
197
+ const parentRelationshipData = {
193
198
  id,
194
199
  type
195
200
  };
196
- let payload;
201
+ let payload = null;
197
202
  if (relationshipKind === 'hasMany') {
198
- payload = relationshipData || [];
203
+ const relData = relationshipData || [];
199
204
  if (relationshipData) {
205
+ assert('expected the relationship data to be an array', Array.isArray(relationshipData));
200
206
  // these arrays could be massive so this is better than filter
201
207
  // Note: this is potentially problematic if type/id are not in the
202
208
  // same state of normalization.
203
- let found = relationshipData.find(v => {
209
+ const found = relationshipData.find(v => {
204
210
  return v.type === parentRelationshipData.type && v.id === parentRelationshipData.id;
205
211
  });
206
212
  if (!found) {
207
- payload.push(parentRelationshipData);
213
+ relData.push(parentRelationshipData);
208
214
  }
209
215
  } else {
210
- payload.push(parentRelationshipData);
216
+ relData.push(parentRelationshipData);
211
217
  }
218
+ payload = relData;
212
219
  } else {
213
- payload = relationshipData || {};
214
- Object.assign(payload, parentRelationshipData);
220
+ const relData = relationshipData || {};
221
+ Object.assign(relData, parentRelationshipData);
222
+ payload = relData;
215
223
  }
216
224
  return payload;
217
225
  }
@@ -220,7 +228,7 @@ function validateRelationshipEntry({
220
228
  }, {
221
229
  id: parentModelID
222
230
  }) {
223
- return id && id.toString() === parentModelID;
231
+ return !!id && id.toString() === parentModelID;
224
232
  }
225
233
  const PotentialLegacyOperations = new Set(['findRecord', 'findAll', 'query', 'queryRecord', 'findBelongsTo', 'findHasMany', 'updateRecord', 'createRecord', 'deleteRecord']);
226
234
  const LegacyNetworkHandler = {
@@ -275,11 +283,12 @@ function findBelongsTo(context) {
275
283
  const identifier = identifiers?.[0];
276
284
 
277
285
  // short circuit if we are already loading
278
- let pendingRequest = identifier && store._fetchManager.getPendingFetch(identifier, options);
286
+ const pendingRequest = identifier && store._fetchManager.getPendingFetch(identifier, options);
279
287
  if (pendingRequest) {
280
288
  return pendingRequest;
281
289
  }
282
290
  if (useLink) {
291
+ assert(`Expected a related link when calling store.findBelongsTo, found ${String(links)}`, links && links.related);
283
292
  return _findBelongsTo(store, record, links.related, field, options);
284
293
  }
285
294
  assert(`Expected an identifier`, Array.isArray(identifiers) && identifiers.length === 1);
@@ -315,15 +324,16 @@ function findHasMany(context) {
315
324
  */
316
325
  assert(`You tried to load a hasMany relationship but you have no adapter (for ${record.type})`, adapter);
317
326
  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');
327
+ assert(`Expected a related link when calling store.findhasMany, found ${String(links)}`, links && links.related);
318
328
  return _findHasMany(adapter, store, record, links.related, field, options);
319
329
  }
320
330
 
321
331
  // identifiers case
322
-
332
+ assert(`Expected an array of identifiers to fetch`, Array.isArray(identifiers));
323
333
  const fetches = new Array(identifiers.length);
324
334
  const manager = store._fetchManager;
325
335
  for (let i = 0; i < identifiers.length; i++) {
326
- let identifier = identifiers[i];
336
+ const identifier = identifiers[i];
327
337
  // TODO we probably can be lenient here and return from cache for the isNew case
328
338
  assertIdentifierHasId(identifier);
329
339
  fetches[i] = options.reload ? manager.scheduleFetch(identifier, options, context.request) : manager.fetchDataIfNeededForIdentifier(identifier, options, context.request);
@@ -347,7 +357,7 @@ function saveRecord(context) {
347
357
  return fetchManagerPromise.then(payload => {
348
358
  if (macroCondition(getOwnConfig().debug.LOG_PAYLOADS)) {
349
359
  try {
350
- let payloadCopy = payload ? JSON.parse(JSON.stringify(payload)) : payload;
360
+ const payloadCopy = payload ? JSON.parse(JSON.stringify(payload)) : payload;
351
361
  // eslint-disable-next-line no-console
352
362
  console.log(`EmberData | Payload - ${operation}`, payloadCopy);
353
363
  } catch (e) {
@@ -356,22 +366,22 @@ function saveRecord(context) {
356
366
  }
357
367
  }
358
368
  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
369
  store._join(() => {
370
+ // @ts-expect-error we don't have access to a response in legacy
370
371
  result = store.cache.didCommit(identifier, {
371
372
  request: context.request,
372
373
  content: payload
373
374
  });
374
375
  });
376
+
377
+ // blatantly lie if we were a createRecord request
378
+ // to give some semblance of cache-control to the
379
+ // lifetimes service while legacy is still around
380
+ if (store.lifetimes?.didRequest && operation === 'createRecord') {
381
+ store.lifetimes.didRequest(context.request, {
382
+ status: 201
383
+ }, null, store);
384
+ }
375
385
  return store.peekRecord(result.data);
376
386
  }).catch(e => {
377
387
  let err = e;
@@ -386,12 +396,12 @@ function saveRecord(context) {
386
396
  }
387
397
  function adapterDidInvalidate(store, identifier, error) {
388
398
  if (error && error.isAdapterError === true && error.code === 'InvalidError') {
389
- let serializer = store.serializerFor(identifier.type);
399
+ const serializer = store.serializerFor(identifier.type);
390
400
 
391
401
  // TODO @deprecate extractErrors being called
392
402
  // TODO remove extractErrors from the default serializers.
393
403
  if (serializer && typeof serializer.extractErrors === 'function') {
394
- let errorsHash = serializer.extractErrors(store, store.modelFor(identifier.type), error, identifier.id);
404
+ const errorsHash = serializer.extractErrors(store, store.modelFor(identifier.type), error, identifier.id);
395
405
  error.errors = errorsHashToArray(errorsHash);
396
406
  }
397
407
  }
@@ -421,7 +431,7 @@ function errorsHashToArray(errors) {
421
431
  const out = [];
422
432
  if (errors) {
423
433
  Object.keys(errors).forEach(key => {
424
- let messages = makeArray(errors[key]);
434
+ const messages = makeArray(errors[key]);
425
435
  for (let i = 0; i < messages.length; i++) {
426
436
  let title = 'Invalid Attribute';
427
437
  let pointer = `/data/attributes/${key}`;
@@ -462,7 +472,7 @@ function findRecord(context) {
462
472
  promise = store._fetchManager.scheduleFetch(identifier, options, context.request);
463
473
  } else {
464
474
  let snapshot = null;
465
- let adapter = store.adapterFor(identifier.type);
475
+ const adapter = store.adapterFor(identifier.type);
466
476
 
467
477
  // Refetch the record if the adapter thinks the record is stale
468
478
  if (typeof options.reload === 'undefined' && adapter.shouldReloadRecord && adapter.shouldReloadRecord(store, snapshot = store._fetchManager.createSnapshot(identifier, options))) {
@@ -577,7 +587,7 @@ function query(context) {
577
587
  delete options._recordArray;
578
588
  }
579
589
  const schema = store.modelFor(type);
580
- let promise = Promise.resolve().then(() => adapter.query(store, schema, query, recordArray, options));
590
+ const promise = Promise.resolve().then(() => adapter.query(store, schema, query, recordArray, options));
581
591
  return promise.then(adapterPayload => {
582
592
  const serializer = store.serializerFor(type);
583
593
  const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'query');
@@ -605,7 +615,7 @@ function queryRecord(context) {
605
615
  assert(`You tried to make a query but you have no adapter (for ${type})`, adapter);
606
616
  assert(`You tried to make a query but your adapter does not implement 'queryRecord'`, typeof adapter.queryRecord === 'function');
607
617
  const schema = store.modelFor(type);
608
- let promise = Promise.resolve().then(() => adapter.queryRecord(store, schema, query, options));
618
+ const promise = Promise.resolve().then(() => adapter.queryRecord(store, schema, query, options));
609
619
  return promise.then(adapterPayload => {
610
620
  const serializer = store.serializerFor(type);
611
621
  const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'queryRecord');
@@ -614,4 +624,227 @@ function queryRecord(context) {
614
624
  return identifier ? store.peekRecord(identifier) : null;
615
625
  });
616
626
  }
617
- export { LegacyNetworkHandler };
627
+
628
+ /**
629
+ * @module @ember-data/store
630
+ * @class Store
631
+ */
632
+
633
+ /**
634
+ Returns an instance of the adapter for a given type. For
635
+ example, `adapterFor('person')` will return an instance of
636
+ the adapter located at `app/adapters/person.js`
637
+
638
+ If no `person` adapter is found, this method will look
639
+ for an `application` adapter (the default adapter for
640
+ your entire application).
641
+
642
+ @method adapterFor
643
+ @public
644
+ @param {String} modelName
645
+ @return Adapter
646
+ */
647
+
648
+ function adapterFor(modelName, _allowMissing) {
649
+ assert(`Attempted to call store.adapterFor(), but the store instance has already been destroyed.`, !(this.isDestroying || this.isDestroyed));
650
+ assert(`You need to pass a model name to the store's adapterFor method`, modelName);
651
+ assert(`Passing classes to store.adapterFor has been removed. Please pass a dasherized string instead of ${modelName}`, typeof modelName === 'string');
652
+ this._adapterCache = this._adapterCache || Object.create(null);
653
+ const normalizedModelName = _deprecatingNormalize(modelName);
654
+ const {
655
+ _adapterCache
656
+ } = this;
657
+ let adapter = _adapterCache[normalizedModelName];
658
+ if (adapter) {
659
+ return adapter;
660
+ }
661
+ const owner = getOwner(this);
662
+
663
+ // name specific adapter
664
+ adapter = owner.lookup(`adapter:${normalizedModelName}`);
665
+ if (adapter !== undefined) {
666
+ _adapterCache[normalizedModelName] = adapter;
667
+ return adapter;
668
+ }
669
+
670
+ // no adapter found for the specific name, fallback and check for application adapter
671
+ adapter = _adapterCache.application || owner.lookup('adapter:application');
672
+ if (adapter !== undefined) {
673
+ _adapterCache[normalizedModelName] = adapter;
674
+ _adapterCache.application = adapter;
675
+ return adapter;
676
+ }
677
+ assert(`No adapter was found for '${modelName}' and no 'application' adapter was found as a fallback.`, _allowMissing);
678
+ }
679
+
680
+ /**
681
+ Returns an instance of the serializer for a given type. For
682
+ example, `serializerFor('person')` will return an instance of
683
+ `App.PersonSerializer`.
684
+
685
+ If no `App.PersonSerializer` is found, this method will look
686
+ for an `App.ApplicationSerializer` (the default serializer for
687
+ your entire application).
688
+
689
+ If a serializer cannot be found on the adapter, it will fall back
690
+ to an instance of `JSONSerializer`.
691
+
692
+ @method serializerFor
693
+ @public
694
+ @param {String} modelName the record to serialize
695
+ @return {Serializer}
696
+ */
697
+ function serializerFor(modelName) {
698
+ assert(`Attempted to call store.serializerFor(), but the store instance has already been destroyed.`, !(this.isDestroying || this.isDestroyed));
699
+ assert(`You need to pass a model name to the store's serializerFor method`, modelName);
700
+ assert(`Passing classes to store.serializerFor has been removed. Please pass a dasherized string instead of ${modelName}`, typeof modelName === 'string');
701
+ this._serializerCache = this._serializerCache || Object.create(null);
702
+ const normalizedModelName = _deprecatingNormalize(modelName);
703
+ const {
704
+ _serializerCache
705
+ } = this;
706
+ let serializer = _serializerCache[normalizedModelName];
707
+ if (serializer) {
708
+ return serializer;
709
+ }
710
+
711
+ // by name
712
+ const owner = getOwner(this);
713
+ serializer = owner.lookup(`serializer:${normalizedModelName}`);
714
+ if (serializer !== undefined) {
715
+ _serializerCache[normalizedModelName] = serializer;
716
+ return serializer;
717
+ }
718
+
719
+ // no serializer found for the specific model, fallback and check for application serializer
720
+ serializer = _serializerCache.application || owner.lookup('serializer:application');
721
+ if (serializer !== undefined) {
722
+ _serializerCache[normalizedModelName] = serializer;
723
+ _serializerCache.application = serializer;
724
+ return serializer;
725
+ }
726
+ return null;
727
+ }
728
+
729
+ /**
730
+ `normalize` converts a json payload into the normalized form that
731
+ [push](../methods/push?anchor=push) expects.
732
+
733
+ Example
734
+
735
+ ```js
736
+ socket.on('message', function(message) {
737
+ let modelName = message.model;
738
+ let data = message.data;
739
+ store.push(store.normalize(modelName, data));
740
+ });
741
+ ```
742
+
743
+ @method normalize
744
+ @public
745
+ @param {String} modelName The name of the model type for this payload
746
+ @param {Object} payload
747
+ @return {Object} The normalized payload
748
+ */
749
+ // TODO @runspired @deprecate users should call normalize on the associated serializer directly
750
+ function normalize(modelName, payload) {
751
+ assert(`Attempted to call store.normalize(), but the store instance has already been destroyed.`, !(this.isDestroying || this.isDestroyed));
752
+ assert(`You need to pass a model name to the store's normalize method`, modelName);
753
+ assert(`Passing classes to store methods has been removed. Please pass a dasherized string instead of ${typeof modelName}`, typeof modelName === 'string');
754
+ const normalizedModelName = _deprecatingNormalize(modelName);
755
+ const serializer = this.serializerFor(normalizedModelName);
756
+ const schema = this.modelFor(normalizedModelName);
757
+ assert(`You must define a normalize method in your serializer in order to call store.normalize`, typeof serializer?.normalize === 'function');
758
+ return serializer.normalize(schema, payload);
759
+ }
760
+
761
+ /**
762
+ Push some raw data into the store.
763
+
764
+ This method can be used both to push in brand new
765
+ records, as well as to update existing records. You
766
+ can push in more than one type of object at once.
767
+ All objects should be in the format expected by the
768
+ serializer.
769
+
770
+ ```app/serializers/application.js
771
+ import RESTSerializer from '@ember-data/serializer/rest';
772
+
773
+ export default class ApplicationSerializer extends RESTSerializer;
774
+ ```
775
+
776
+ ```js
777
+ let pushData = {
778
+ posts: [
779
+ { id: 1, postTitle: "Great post", commentIds: [2] }
780
+ ],
781
+ comments: [
782
+ { id: 2, commentBody: "Insightful comment" }
783
+ ]
784
+ }
785
+
786
+ store.pushPayload(pushData);
787
+ ```
788
+
789
+ By default, the data will be deserialized using a default
790
+ serializer (the application serializer if it exists).
791
+
792
+ Alternatively, `pushPayload` will accept a model type which
793
+ will determine which serializer will process the payload.
794
+
795
+ ```app/serializers/application.js
796
+ import RESTSerializer from '@ember-data/serializer/rest';
797
+
798
+ export default class ApplicationSerializer extends RESTSerializer;
799
+ ```
800
+
801
+ ```app/serializers/post.js
802
+ import JSONSerializer from '@ember-data/serializer/json';
803
+
804
+ export default JSONSerializer;
805
+ ```
806
+
807
+ ```js
808
+ store.pushPayload(pushData); // Will use the application serializer
809
+ store.pushPayload('post', pushData); // Will use the post serializer
810
+ ```
811
+
812
+ @method pushPayload
813
+ @public
814
+ @param {String} modelName Optionally, a model type used to determine which serializer will be used
815
+ @param {Object} inputPayload
816
+ */
817
+ // TODO @runspired @deprecate pushPayload in favor of looking up the serializer
818
+ function pushPayload(modelName, inputPayload) {
819
+ assert(`Attempted to call store.pushPayload(), but the store instance has already been destroyed.`, !(this.isDestroying || this.isDestroyed));
820
+ const payload = inputPayload || modelName;
821
+ const normalizedModelName = inputPayload ? _deprecatingNormalize(modelName) : 'application';
822
+ const serializer = this.serializerFor(normalizedModelName);
823
+ assert(`You cannot use 'store.pushPayload(<type>, <payload>)' unless the serializer for '${normalizedModelName}' defines 'pushPayload'`, serializer && typeof serializer.pushPayload === 'function');
824
+ serializer.pushPayload(this, payload);
825
+ }
826
+
827
+ // TODO @runspired @deprecate records should implement their own serialization if desired
828
+ function serializeRecord(record, options) {
829
+ // TODO we used to check if the record was destroyed here
830
+ if (!this._fetchManager) {
831
+ this._fetchManager = new FetchManager(this);
832
+ }
833
+ return this._fetchManager.createSnapshot(recordIdentifierFor(record)).serialize(options);
834
+ }
835
+ function cleanup() {
836
+ // enqueue destruction of any adapters/serializers we have created
837
+ for (const adapterName in this._adapterCache) {
838
+ const adapter = this._adapterCache[adapterName];
839
+ if (typeof adapter.destroy === 'function') {
840
+ adapter.destroy();
841
+ }
842
+ }
843
+ for (const serializerName in this._serializerCache) {
844
+ const serializer = this._serializerCache[serializerName];
845
+ if (typeof serializer.destroy === 'function') {
846
+ serializer.destroy();
847
+ }
848
+ }
849
+ }
850
+ export { LegacyNetworkHandler, adapterFor, cleanup, normalize, pushPayload, serializeRecord, serializerFor };