@ember-data/legacy-compat 5.3.0 → 5.3.2

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