@ember-data/legacy-compat 5.4.0-alpha.6 → 5.4.0-alpha.60

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 (51) hide show
  1. package/README.md +8 -0
  2. package/addon/{fetch-manager-0744e8e9.js → -private-DmhhlB_x.js} +83 -70
  3. package/addon/-private-DmhhlB_x.js.map +1 -0
  4. package/addon/-private.js +1 -1
  5. package/addon/builders.js +274 -0
  6. package/addon/builders.js.map +1 -0
  7. package/addon/index.js +310 -76
  8. package/addon/index.js.map +1 -1
  9. package/addon/utils.js +246 -0
  10. package/addon/utils.js.map +1 -0
  11. package/addon-main.js +1 -0
  12. package/package.json +79 -28
  13. package/unstable-preview-types/-private.d.ts +17 -0
  14. package/unstable-preview-types/-private.d.ts.map +1 -0
  15. package/unstable-preview-types/builders/find-all.d.ts +38 -0
  16. package/unstable-preview-types/builders/find-all.d.ts.map +1 -0
  17. package/unstable-preview-types/builders/find-record.d.ts +59 -0
  18. package/unstable-preview-types/builders/find-record.d.ts.map +1 -0
  19. package/unstable-preview-types/builders/query.d.ts +69 -0
  20. package/unstable-preview-types/builders/query.d.ts.map +1 -0
  21. package/unstable-preview-types/builders/save-record.d.ts +37 -0
  22. package/unstable-preview-types/builders/save-record.d.ts.map +1 -0
  23. package/unstable-preview-types/builders/utils.d.ts +6 -0
  24. package/unstable-preview-types/builders/utils.d.ts.map +1 -0
  25. package/unstable-preview-types/builders.d.ts +18 -0
  26. package/unstable-preview-types/builders.d.ts.map +1 -0
  27. package/unstable-preview-types/index.d.ts +161 -0
  28. package/unstable-preview-types/index.d.ts.map +1 -0
  29. package/unstable-preview-types/legacy-network-handler/fetch-manager.d.ts +49 -0
  30. package/unstable-preview-types/legacy-network-handler/fetch-manager.d.ts.map +1 -0
  31. package/unstable-preview-types/legacy-network-handler/identifier-has-id.d.ts +5 -0
  32. package/unstable-preview-types/legacy-network-handler/identifier-has-id.d.ts.map +1 -0
  33. package/unstable-preview-types/legacy-network-handler/legacy-data-fetch.d.ts +14 -0
  34. package/unstable-preview-types/legacy-network-handler/legacy-data-fetch.d.ts.map +1 -0
  35. package/unstable-preview-types/legacy-network-handler/legacy-data-utils.d.ts +8 -0
  36. package/unstable-preview-types/legacy-network-handler/legacy-data-utils.d.ts.map +1 -0
  37. package/unstable-preview-types/legacy-network-handler/legacy-network-handler.d.ts +5 -0
  38. package/unstable-preview-types/legacy-network-handler/legacy-network-handler.d.ts.map +1 -0
  39. package/unstable-preview-types/legacy-network-handler/minimum-adapter-interface.d.ts +549 -0
  40. package/unstable-preview-types/legacy-network-handler/minimum-adapter-interface.d.ts.map +1 -0
  41. package/unstable-preview-types/legacy-network-handler/minimum-serializer-interface.d.ts +235 -0
  42. package/unstable-preview-types/legacy-network-handler/minimum-serializer-interface.d.ts.map +1 -0
  43. package/unstable-preview-types/legacy-network-handler/serializer-response.d.ts +9 -0
  44. package/unstable-preview-types/legacy-network-handler/serializer-response.d.ts.map +1 -0
  45. package/unstable-preview-types/legacy-network-handler/snapshot-record-array.d.ts +97 -0
  46. package/unstable-preview-types/legacy-network-handler/snapshot-record-array.d.ts.map +1 -0
  47. package/unstable-preview-types/legacy-network-handler/snapshot.d.ts +248 -0
  48. package/unstable-preview-types/legacy-network-handler/snapshot.d.ts.map +1 -0
  49. package/unstable-preview-types/utils.d.ts +159 -0
  50. package/unstable-preview-types/utils.d.ts.map +1 -0
  51. 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);
@@ -340,6 +350,7 @@ function saveRecord(context) {
340
350
  options,
341
351
  record: identifier
342
352
  } = data;
353
+ store.cache.willCommit(identifier, context);
343
354
  const saveOptions = Object.assign({
344
355
  [SaveOp]: operation
345
356
  }, options);
@@ -347,7 +358,7 @@ function saveRecord(context) {
347
358
  return fetchManagerPromise.then(payload => {
348
359
  if (macroCondition(getOwnConfig().debug.LOG_PAYLOADS)) {
349
360
  try {
350
- let payloadCopy = payload ? JSON.parse(JSON.stringify(payload)) : payload;
361
+ const payloadCopy = payload ? JSON.parse(JSON.stringify(payload)) : payload;
351
362
  // eslint-disable-next-line no-console
352
363
  console.log(`EmberData | Payload - ${operation}`, payloadCopy);
353
364
  } catch (e) {
@@ -356,22 +367,22 @@ function saveRecord(context) {
356
367
  }
357
368
  }
358
369
  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
370
  store._join(() => {
371
+ // @ts-expect-error we don't have access to a response in legacy
370
372
  result = store.cache.didCommit(identifier, {
371
373
  request: context.request,
372
374
  content: payload
373
375
  });
374
376
  });
377
+
378
+ // blatantly lie if we were a createRecord request
379
+ // to give some semblance of cache-control to the
380
+ // lifetimes service while legacy is still around
381
+ if (store.lifetimes?.didRequest && operation === 'createRecord') {
382
+ store.lifetimes.didRequest(context.request, {
383
+ status: 201
384
+ }, null, store);
385
+ }
375
386
  return store.peekRecord(result.data);
376
387
  }).catch(e => {
377
388
  let err = e;
@@ -386,12 +397,12 @@ function saveRecord(context) {
386
397
  }
387
398
  function adapterDidInvalidate(store, identifier, error) {
388
399
  if (error && error.isAdapterError === true && error.code === 'InvalidError') {
389
- let serializer = store.serializerFor(identifier.type);
400
+ const serializer = store.serializerFor(identifier.type);
390
401
 
391
402
  // TODO @deprecate extractErrors being called
392
403
  // TODO remove extractErrors from the default serializers.
393
404
  if (serializer && typeof serializer.extractErrors === 'function') {
394
- let errorsHash = serializer.extractErrors(store, store.modelFor(identifier.type), error, identifier.id);
405
+ const errorsHash = serializer.extractErrors(store, store.modelFor(identifier.type), error, identifier.id);
395
406
  error.errors = errorsHashToArray(errorsHash);
396
407
  }
397
408
  }
@@ -421,7 +432,7 @@ function errorsHashToArray(errors) {
421
432
  const out = [];
422
433
  if (errors) {
423
434
  Object.keys(errors).forEach(key => {
424
- let messages = makeArray(errors[key]);
435
+ const messages = makeArray(errors[key]);
425
436
  for (let i = 0; i < messages.length; i++) {
426
437
  let title = 'Invalid Attribute';
427
438
  let pointer = `/data/attributes/${key}`;
@@ -462,7 +473,7 @@ function findRecord(context) {
462
473
  promise = store._fetchManager.scheduleFetch(identifier, options, context.request);
463
474
  } else {
464
475
  let snapshot = null;
465
- let adapter = store.adapterFor(identifier.type);
476
+ const adapter = store.adapterFor(identifier.type);
466
477
 
467
478
  // Refetch the record if the adapter thinks the record is stale
468
479
  if (typeof options.reload === 'undefined' && adapter.shouldReloadRecord && adapter.shouldReloadRecord(store, snapshot = store._fetchManager.createSnapshot(identifier, options))) {
@@ -577,7 +588,7 @@ function query(context) {
577
588
  delete options._recordArray;
578
589
  }
579
590
  const schema = store.modelFor(type);
580
- let promise = Promise.resolve().then(() => adapter.query(store, schema, query, recordArray, options));
591
+ const promise = Promise.resolve().then(() => adapter.query(store, schema, query, recordArray, options));
581
592
  return promise.then(adapterPayload => {
582
593
  const serializer = store.serializerFor(type);
583
594
  const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'query');
@@ -605,7 +616,7 @@ function queryRecord(context) {
605
616
  assert(`You tried to make a query but you have no adapter (for ${type})`, adapter);
606
617
  assert(`You tried to make a query but your adapter does not implement 'queryRecord'`, typeof adapter.queryRecord === 'function');
607
618
  const schema = store.modelFor(type);
608
- let promise = Promise.resolve().then(() => adapter.queryRecord(store, schema, query, options));
619
+ const promise = Promise.resolve().then(() => adapter.queryRecord(store, schema, query, options));
609
620
  return promise.then(adapterPayload => {
610
621
  const serializer = store.serializerFor(type);
611
622
  const payload = normalizeResponseHelper(serializer, store, schema, adapterPayload, null, 'queryRecord');
@@ -614,4 +625,227 @@ function queryRecord(context) {
614
625
  return identifier ? store.peekRecord(identifier) : null;
615
626
  });
616
627
  }
617
- export { LegacyNetworkHandler };
628
+
629
+ /**
630
+ * @module @ember-data/store
631
+ * @class Store
632
+ */
633
+
634
+ /**
635
+ Returns an instance of the adapter for a given type. For
636
+ example, `adapterFor('person')` will return an instance of
637
+ the adapter located at `app/adapters/person.js`
638
+
639
+ If no `person` adapter is found, this method will look
640
+ for an `application` adapter (the default adapter for
641
+ your entire application).
642
+
643
+ @method adapterFor
644
+ @public
645
+ @param {String} modelName
646
+ @return Adapter
647
+ */
648
+
649
+ function adapterFor(modelName, _allowMissing) {
650
+ assert(`Attempted to call store.adapterFor(), but the store instance has already been destroyed.`, !(this.isDestroying || this.isDestroyed));
651
+ assert(`You need to pass a model name to the store's adapterFor method`, modelName);
652
+ assert(`Passing classes to store.adapterFor has been removed. Please pass a dasherized string instead of ${modelName}`, typeof modelName === 'string');
653
+ this._adapterCache = this._adapterCache || Object.create(null);
654
+ const normalizedModelName = _deprecatingNormalize(modelName);
655
+ const {
656
+ _adapterCache
657
+ } = this;
658
+ let adapter = _adapterCache[normalizedModelName];
659
+ if (adapter) {
660
+ return adapter;
661
+ }
662
+ const owner = getOwner(this);
663
+
664
+ // name specific adapter
665
+ adapter = owner.lookup(`adapter:${normalizedModelName}`);
666
+ if (adapter !== undefined) {
667
+ _adapterCache[normalizedModelName] = adapter;
668
+ return adapter;
669
+ }
670
+
671
+ // no adapter found for the specific name, fallback and check for application adapter
672
+ adapter = _adapterCache.application || owner.lookup('adapter:application');
673
+ if (adapter !== undefined) {
674
+ _adapterCache[normalizedModelName] = adapter;
675
+ _adapterCache.application = adapter;
676
+ return adapter;
677
+ }
678
+ assert(`No adapter was found for '${modelName}' and no 'application' adapter was found as a fallback.`, _allowMissing);
679
+ }
680
+
681
+ /**
682
+ Returns an instance of the serializer for a given type. For
683
+ example, `serializerFor('person')` will return an instance of
684
+ `App.PersonSerializer`.
685
+
686
+ If no `App.PersonSerializer` is found, this method will look
687
+ for an `App.ApplicationSerializer` (the default serializer for
688
+ your entire application).
689
+
690
+ If a serializer cannot be found on the adapter, it will fall back
691
+ to an instance of `JSONSerializer`.
692
+
693
+ @method serializerFor
694
+ @public
695
+ @param {String} modelName the record to serialize
696
+ @return {Serializer}
697
+ */
698
+ function serializerFor(modelName) {
699
+ assert(`Attempted to call store.serializerFor(), but the store instance has already been destroyed.`, !(this.isDestroying || this.isDestroyed));
700
+ assert(`You need to pass a model name to the store's serializerFor method`, modelName);
701
+ assert(`Passing classes to store.serializerFor has been removed. Please pass a dasherized string instead of ${modelName}`, typeof modelName === 'string');
702
+ this._serializerCache = this._serializerCache || Object.create(null);
703
+ const normalizedModelName = _deprecatingNormalize(modelName);
704
+ const {
705
+ _serializerCache
706
+ } = this;
707
+ let serializer = _serializerCache[normalizedModelName];
708
+ if (serializer) {
709
+ return serializer;
710
+ }
711
+
712
+ // by name
713
+ const owner = getOwner(this);
714
+ serializer = owner.lookup(`serializer:${normalizedModelName}`);
715
+ if (serializer !== undefined) {
716
+ _serializerCache[normalizedModelName] = serializer;
717
+ return serializer;
718
+ }
719
+
720
+ // no serializer found for the specific model, fallback and check for application serializer
721
+ serializer = _serializerCache.application || owner.lookup('serializer:application');
722
+ if (serializer !== undefined) {
723
+ _serializerCache[normalizedModelName] = serializer;
724
+ _serializerCache.application = serializer;
725
+ return serializer;
726
+ }
727
+ return null;
728
+ }
729
+
730
+ /**
731
+ `normalize` converts a json payload into the normalized form that
732
+ [push](../methods/push?anchor=push) expects.
733
+
734
+ Example
735
+
736
+ ```js
737
+ socket.on('message', function(message) {
738
+ let modelName = message.model;
739
+ let data = message.data;
740
+ store.push(store.normalize(modelName, data));
741
+ });
742
+ ```
743
+
744
+ @method normalize
745
+ @public
746
+ @param {String} modelName The name of the model type for this payload
747
+ @param {Object} payload
748
+ @return {Object} The normalized payload
749
+ */
750
+ // TODO @runspired @deprecate users should call normalize on the associated serializer directly
751
+ function normalize(modelName, payload) {
752
+ assert(`Attempted to call store.normalize(), but the store instance has already been destroyed.`, !(this.isDestroying || this.isDestroyed));
753
+ assert(`You need to pass a model name to the store's normalize method`, modelName);
754
+ assert(`Passing classes to store methods has been removed. Please pass a dasherized string instead of ${typeof modelName}`, typeof modelName === 'string');
755
+ const normalizedModelName = _deprecatingNormalize(modelName);
756
+ const serializer = this.serializerFor(normalizedModelName);
757
+ const schema = this.modelFor(normalizedModelName);
758
+ assert(`You must define a normalize method in your serializer in order to call store.normalize`, typeof serializer?.normalize === 'function');
759
+ return serializer.normalize(schema, payload);
760
+ }
761
+
762
+ /**
763
+ Push some raw data into the store.
764
+
765
+ This method can be used both to push in brand new
766
+ records, as well as to update existing records. You
767
+ can push in more than one type of object at once.
768
+ All objects should be in the format expected by the
769
+ serializer.
770
+
771
+ ```app/serializers/application.js
772
+ import RESTSerializer from '@ember-data/serializer/rest';
773
+
774
+ export default class ApplicationSerializer extends RESTSerializer;
775
+ ```
776
+
777
+ ```js
778
+ let pushData = {
779
+ posts: [
780
+ { id: 1, postTitle: "Great post", commentIds: [2] }
781
+ ],
782
+ comments: [
783
+ { id: 2, commentBody: "Insightful comment" }
784
+ ]
785
+ }
786
+
787
+ store.pushPayload(pushData);
788
+ ```
789
+
790
+ By default, the data will be deserialized using a default
791
+ serializer (the application serializer if it exists).
792
+
793
+ Alternatively, `pushPayload` will accept a model type which
794
+ will determine which serializer will process the payload.
795
+
796
+ ```app/serializers/application.js
797
+ import RESTSerializer from '@ember-data/serializer/rest';
798
+
799
+ export default class ApplicationSerializer extends RESTSerializer;
800
+ ```
801
+
802
+ ```app/serializers/post.js
803
+ import JSONSerializer from '@ember-data/serializer/json';
804
+
805
+ export default JSONSerializer;
806
+ ```
807
+
808
+ ```js
809
+ store.pushPayload(pushData); // Will use the application serializer
810
+ store.pushPayload('post', pushData); // Will use the post serializer
811
+ ```
812
+
813
+ @method pushPayload
814
+ @public
815
+ @param {String} modelName Optionally, a model type used to determine which serializer will be used
816
+ @param {Object} inputPayload
817
+ */
818
+ // TODO @runspired @deprecate pushPayload in favor of looking up the serializer
819
+ function pushPayload(modelName, inputPayload) {
820
+ assert(`Attempted to call store.pushPayload(), but the store instance has already been destroyed.`, !(this.isDestroying || this.isDestroyed));
821
+ const payload = inputPayload || modelName;
822
+ const normalizedModelName = inputPayload ? _deprecatingNormalize(modelName) : 'application';
823
+ const serializer = this.serializerFor(normalizedModelName);
824
+ assert(`You cannot use 'store.pushPayload(<type>, <payload>)' unless the serializer for '${normalizedModelName}' defines 'pushPayload'`, serializer && typeof serializer.pushPayload === 'function');
825
+ serializer.pushPayload(this, payload);
826
+ }
827
+
828
+ // TODO @runspired @deprecate records should implement their own serialization if desired
829
+ function serializeRecord(record, options) {
830
+ // TODO we used to check if the record was destroyed here
831
+ if (!this._fetchManager) {
832
+ this._fetchManager = new FetchManager(this);
833
+ }
834
+ return this._fetchManager.createSnapshot(recordIdentifierFor(record)).serialize(options);
835
+ }
836
+ function cleanup() {
837
+ // enqueue destruction of any adapters/serializers we have created
838
+ for (const adapterName in this._adapterCache) {
839
+ const adapter = this._adapterCache[adapterName];
840
+ if (typeof adapter.destroy === 'function') {
841
+ adapter.destroy();
842
+ }
843
+ }
844
+ for (const serializerName in this._serializerCache) {
845
+ const serializer = this._serializerCache[serializerName];
846
+ if (typeof serializer.destroy === 'function') {
847
+ serializer.destroy();
848
+ }
849
+ }
850
+ }
851
+ export { LegacyNetworkHandler, adapterFor, cleanup, normalize, pushPayload, serializeRecord, serializerFor };