@ember-data-mirror/serializer 5.4.0-alpha.64 → 5.4.0-alpha.70

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 (58) hide show
  1. package/addon-main.cjs +5 -0
  2. package/blueprints/serializer/index.js +71 -5
  3. package/blueprints/serializer-test/index.js +13 -7
  4. package/blueprints/serializer-test/qunit-files/__root__/__path__/__test__.js +8 -9
  5. package/blueprints/transform/index.js +14 -4
  6. package/blueprints/transform-test/index.js +13 -7
  7. package/blueprints/transform-test/qunit-files/__root__/__path__/__test__.js +3 -4
  8. package/dist/index.js +373 -0
  9. package/dist/index.js.map +1 -0
  10. package/{addon/json.js → dist/json-CsNumir-.js} +26 -7
  11. package/dist/json-CsNumir-.js.map +1 -0
  12. package/{addon → dist}/json-api.js +38 -16
  13. package/dist/json-api.js.map +1 -0
  14. package/dist/json.js +7 -0
  15. package/dist/json.js.map +1 -0
  16. package/dist/rest.js +1271 -0
  17. package/dist/rest.js.map +1 -0
  18. package/{addon/string-Juwz4cu0.js → dist/transform.js} +5 -13
  19. package/dist/transform.js.map +1 -0
  20. package/package.json +36 -43
  21. package/unstable-preview-types/-private/embedded-records-mixin.d.ts +98 -2
  22. package/unstable-preview-types/-private/embedded-records-mixin.d.ts.map +1 -1
  23. package/unstable-preview-types/-private/transforms/boolean.d.ts +1 -1
  24. package/unstable-preview-types/-private/transforms/boolean.d.ts.map +1 -1
  25. package/unstable-preview-types/-private/transforms/date.d.ts +1 -1
  26. package/unstable-preview-types/-private/transforms/date.d.ts.map +1 -1
  27. package/unstable-preview-types/-private/transforms/number.d.ts +1 -1
  28. package/unstable-preview-types/-private/transforms/number.d.ts.map +1 -1
  29. package/unstable-preview-types/-private/transforms/string.d.ts +1 -1
  30. package/unstable-preview-types/-private/transforms/string.d.ts.map +1 -1
  31. package/unstable-preview-types/-private/transforms/transform.d.ts +5 -6
  32. package/unstable-preview-types/-private/transforms/transform.d.ts.map +1 -1
  33. package/unstable-preview-types/index.d.ts +5 -6
  34. package/unstable-preview-types/index.d.ts.map +1 -1
  35. package/unstable-preview-types/json-api.d.ts.map +1 -1
  36. package/unstable-preview-types/json.d.ts.map +1 -1
  37. package/unstable-preview-types/rest.d.ts +1 -1
  38. package/unstable-preview-types/rest.d.ts.map +1 -1
  39. package/unstable-preview-types/transform.d.ts +5 -1
  40. package/unstable-preview-types/transform.d.ts.map +1 -1
  41. package/addon/-private.js +0 -3
  42. package/addon/-private.js.map +0 -1
  43. package/addon/embedded-records-mixin-Lr-0FvWz.js +0 -578
  44. package/addon/embedded-records-mixin-Lr-0FvWz.js.map +0 -1
  45. package/addon/index.js +0 -181
  46. package/addon/index.js.map +0 -1
  47. package/addon/json-api.js.map +0 -1
  48. package/addon/json.js.map +0 -1
  49. package/addon/rest.js +0 -684
  50. package/addon/rest.js.map +0 -1
  51. package/addon/string-Juwz4cu0.js.map +0 -1
  52. package/addon/transform.js +0 -1
  53. package/addon/transform.js.map +0 -1
  54. package/addon/utils-NcVD2Jb5.js +0 -12
  55. package/addon/utils-NcVD2Jb5.js.map +0 -1
  56. package/addon-main.js +0 -94
  57. package/unstable-preview-types/-private.d.ts +0 -13
  58. package/unstable-preview-types/-private.d.ts.map +0 -1
package/dist/rest.js ADDED
@@ -0,0 +1,1271 @@
1
+ import { warn } from '@ember/debug';
2
+ import { camelize, dasherize } from '@ember/string';
3
+ import { singularize } from 'ember-inflector';
4
+ import { J as JSONSerializer, c as coerceId } from "./json-CsNumir-";
5
+ import { macroCondition, getGlobalConfig } from '@embroider/macros';
6
+ import Mixin from '@ember/object/mixin';
7
+
8
+ /**
9
+ @module @ember-data-mirror/serializer/rest
10
+ */
11
+
12
+ /**
13
+ ## Using Embedded Records
14
+
15
+ `EmbeddedRecordsMixin` supports serializing embedded records.
16
+
17
+ To set up embedded records, include the mixin when extending a serializer,
18
+ then define and configure embedded (model) relationships.
19
+
20
+ Note that embedded records will serialize with the serializer for their model instead of the serializer in which they are defined.
21
+
22
+ Note also that this mixin does not work with JSONAPISerializer because the JSON:API specification does not describe how to format embedded resources.
23
+
24
+ Below is an example of a per-type serializer (`post` type).
25
+
26
+ ```app/serializers/post.js
27
+ import RESTSerializer, { EmbeddedRecordsMixin } from '@ember-data-mirror/serializer/rest';
28
+
29
+ export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
30
+ attrs = {
31
+ author: { embedded: 'always' },
32
+ comments: { serialize: 'ids' }
33
+ }
34
+ }
35
+ ```
36
+ Note that this use of `{ embedded: 'always' }` is unrelated to
37
+ the `{ embedded: 'always' }` that is defined as an option on `attr` as part of
38
+ defining a model while working with the `ActiveModelSerializer`. Nevertheless,
39
+ using `{ embedded: 'always' }` as an option to `attr` is not a valid way to set up
40
+ embedded records.
41
+
42
+ The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for:
43
+
44
+ ```js
45
+ {
46
+ serialize: 'records',
47
+ deserialize: 'records'
48
+ }
49
+ ```
50
+
51
+ ### Configuring Attrs
52
+
53
+ A resource's `attrs` option may be set to use `ids`, `records` or false for the
54
+ `serialize` and `deserialize` settings.
55
+
56
+ The `attrs` property can be set on the `ApplicationSerializer` or a per-type
57
+ serializer.
58
+
59
+ In the case where embedded JSON is expected while extracting a payload (reading)
60
+ the setting is `deserialize: 'records'`, there is no need to use `ids` when
61
+ extracting as that is the default behaviour without this mixin if you are using
62
+ the vanilla `EmbeddedRecordsMixin`. Likewise, to embed JSON in the payload while
63
+ serializing `serialize: 'records'` is the setting to use. There is an option of
64
+ not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you
65
+ do not want the relationship sent at all, you can use `serialize: false`.
66
+
67
+
68
+ ### EmbeddedRecordsMixin defaults
69
+ If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin`
70
+ will behave in the following way:
71
+
72
+ BelongsTo: `{ serialize: 'id', deserialize: 'id' }`
73
+ HasMany: `{ serialize: false, deserialize: 'ids' }`
74
+
75
+ ### Model Relationships
76
+
77
+ Embedded records must have a model defined to be extracted and serialized. Note that
78
+ when defining any relationships on your model such as `belongsTo` and `hasMany`, you
79
+ should not both specify `async: true` and also indicate through the serializer's
80
+ `attrs` attribute that the related model should be embedded for deserialization.
81
+ If a model is declared embedded for deserialization (`embedded: 'always'` or `deserialize: 'records'`),
82
+ then do not use `async: true`.
83
+
84
+ To successfully extract and serialize embedded records the model relationships
85
+ must be set up correctly. See the
86
+ [defining relationships](https://guides.emberjs.com/current/models/relationships)
87
+ section of the **Defining Models** guide page.
88
+
89
+ Records without an `id` property are not considered embedded records, model
90
+ instances must have an `id` property to be used with Ember Data.
91
+
92
+ ### Example JSON payloads, Models and Serializers
93
+
94
+ **When customizing a serializer it is important to grok what the customizations
95
+ are. Please read the docs for the methods this mixin provides, in case you need
96
+ to modify it to fit your specific needs.**
97
+
98
+ For example, review the docs for each method of this mixin:
99
+ * [normalize](/ember-data/release/classes/EmbeddedRecordsMixin/methods/normalize?anchor=normalize)
100
+ * [serializeBelongsTo](/ember-data/release/classes/EmbeddedRecordsMixin/methods/serializeBelongsTo?anchor=serializeBelongsTo)
101
+ * [serializeHasMany](/ember-data/release/classes/EmbeddedRecordsMixin/methods/serializeHasMany?anchor=serializeHasMany)
102
+
103
+ @class EmbeddedRecordsMixin
104
+ @public
105
+ */
106
+ const EmbeddedRecordsMixin = Mixin.create({
107
+ /**
108
+ Normalize the record and recursively normalize/extract all the embedded records
109
+ while pushing them into the store as they are encountered
110
+ A payload with an attr configured for embedded records needs to be extracted:
111
+ ```js
112
+ {
113
+ "post": {
114
+ "id": "1"
115
+ "title": "Rails is omakase",
116
+ "comments": [{
117
+ "id": "1",
118
+ "body": "Rails is unagi"
119
+ }, {
120
+ "id": "2",
121
+ "body": "Omakase O_o"
122
+ }]
123
+ }
124
+ }
125
+ ```
126
+ @method normalize
127
+ @public
128
+ @param {Model} typeClass
129
+ @param {Object} hash to be normalized
130
+ @param {String} prop the hash has been referenced by
131
+ @return {Object} the normalized hash
132
+ **/
133
+ normalize(typeClass, hash, prop) {
134
+ const normalizedHash = this._super(typeClass, hash, prop);
135
+ return this._extractEmbeddedRecords(this, this.store, typeClass, normalizedHash);
136
+ },
137
+ keyForRelationship(key, typeClass, method) {
138
+ if (method === 'serialize' && this.hasSerializeRecordsOption(key) || method === 'deserialize' && this.hasDeserializeRecordsOption(key)) {
139
+ return this.keyForAttribute(key, method);
140
+ } else {
141
+ return this._super(key, typeClass, method) || key;
142
+ }
143
+ },
144
+ /**
145
+ Serialize `belongsTo` relationship when it is configured as an embedded object.
146
+ This example of an author model belongs to a post model:
147
+ ```js
148
+ import Model, { attr, belongsTo } from '@ember-data-mirror/model';
149
+ Post = Model.extend({
150
+ title: attr('string'),
151
+ body: attr('string'),
152
+ author: belongsTo('author')
153
+ });
154
+ Author = Model.extend({
155
+ name: attr('string'),
156
+ post: belongsTo('post')
157
+ });
158
+ ```
159
+ Use a custom (type) serializer for the post model to configure embedded author
160
+ ```app/serializers/post.js
161
+ import RESTSerializer, { EmbeddedRecordsMixin } from '@ember-data-mirror/serializer/rest';
162
+ export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
163
+ attrs = {
164
+ author: { embedded: 'always' }
165
+ }
166
+ }
167
+ ```
168
+ A payload with an attribute configured for embedded records can serialize
169
+ the records together under the root attribute's payload:
170
+ ```js
171
+ {
172
+ "post": {
173
+ "id": "1"
174
+ "title": "Rails is omakase",
175
+ "author": {
176
+ "id": "2"
177
+ "name": "dhh"
178
+ }
179
+ }
180
+ }
181
+ ```
182
+ @method serializeBelongsTo
183
+ @public
184
+ @param {Snapshot} snapshot
185
+ @param {Object} json
186
+ @param {Object} relationship
187
+ */
188
+ serializeBelongsTo(snapshot, json, relationship) {
189
+ const attr = relationship.name;
190
+ if (this.noSerializeOptionSpecified(attr)) {
191
+ this._super(snapshot, json, relationship);
192
+ return;
193
+ }
194
+ const includeIds = this.hasSerializeIdsOption(attr);
195
+ const includeRecords = this.hasSerializeRecordsOption(attr);
196
+ const embeddedSnapshot = snapshot.belongsTo(attr);
197
+ if (includeIds) {
198
+ const schema = this.store.modelFor(snapshot.modelName);
199
+ let serializedKey = this._getMappedKey(relationship.name, schema);
200
+ if (serializedKey === relationship.name && this.keyForRelationship) {
201
+ serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
202
+ }
203
+ if (!embeddedSnapshot) {
204
+ json[serializedKey] = null;
205
+ } else {
206
+ json[serializedKey] = embeddedSnapshot.id;
207
+ if (relationship.options.polymorphic) {
208
+ this.serializePolymorphicType(snapshot, json, relationship);
209
+ }
210
+ }
211
+ } else if (includeRecords) {
212
+ this._serializeEmbeddedBelongsTo(snapshot, json, relationship);
213
+ }
214
+ },
215
+ _serializeEmbeddedBelongsTo(snapshot, json, relationship) {
216
+ const embeddedSnapshot = snapshot.belongsTo(relationship.name);
217
+ const schema = this.store.modelFor(snapshot.modelName);
218
+ let serializedKey = this._getMappedKey(relationship.name, schema);
219
+ if (serializedKey === relationship.name && this.keyForRelationship) {
220
+ serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
221
+ }
222
+ if (!embeddedSnapshot) {
223
+ json[serializedKey] = null;
224
+ } else {
225
+ json[serializedKey] = embeddedSnapshot.serialize({
226
+ includeId: true
227
+ });
228
+ this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[serializedKey]);
229
+ if (relationship.options.polymorphic) {
230
+ this.serializePolymorphicType(snapshot, json, relationship);
231
+ }
232
+ }
233
+ },
234
+ /**
235
+ Serializes `hasMany` relationships when it is configured as embedded objects.
236
+ This example of a post model has many comments:
237
+ ```js
238
+ import Model, { attr, belongsTo, hasMany } from '@ember-data-mirror/model';
239
+ Post = Model.extend({
240
+ title: attr('string'),
241
+ body: attr('string'),
242
+ comments: hasMany('comment')
243
+ });
244
+ Comment = Model.extend({
245
+ body: attr('string'),
246
+ post: belongsTo('post')
247
+ });
248
+ ```
249
+ Use a custom (type) serializer for the post model to configure embedded comments
250
+ ```app/serializers/post.js
251
+ import RESTSerializer, { EmbeddedRecordsMixin } from '@ember-data-mirror/serializer/rest';
252
+ export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
253
+ attrs = {
254
+ comments: { embedded: 'always' }
255
+ }
256
+ }
257
+ ```
258
+ A payload with an attribute configured for embedded records can serialize
259
+ the records together under the root attribute's payload:
260
+ ```js
261
+ {
262
+ "post": {
263
+ "id": "1"
264
+ "title": "Rails is omakase",
265
+ "body": "I want this for my ORM, I want that for my template language..."
266
+ "comments": [{
267
+ "id": "1",
268
+ "body": "Rails is unagi"
269
+ }, {
270
+ "id": "2",
271
+ "body": "Omakase O_o"
272
+ }]
273
+ }
274
+ }
275
+ ```
276
+ The attrs options object can use more specific instruction for extracting and
277
+ serializing. When serializing, an option to embed `ids`, `ids-and-types` or `records` can be set.
278
+ When extracting the only option is `records`.
279
+ So `{ embedded: 'always' }` is shorthand for:
280
+ `{ serialize: 'records', deserialize: 'records' }`
281
+ To embed the `ids` for a related object (using a hasMany relationship):
282
+ ```app/serializers/post.js
283
+ import RESTSerializer, { EmbeddedRecordsMixin } from '@ember-data-mirror/serializer/rest';
284
+ export default class PostSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
285
+ attrs = {
286
+ comments: { serialize: 'ids', deserialize: 'records' }
287
+ }
288
+ }
289
+ ```
290
+ ```js
291
+ {
292
+ "post": {
293
+ "id": "1"
294
+ "title": "Rails is omakase",
295
+ "body": "I want this for my ORM, I want that for my template language..."
296
+ "comments": ["1", "2"]
297
+ }
298
+ }
299
+ ```
300
+ To embed the relationship as a collection of objects with `id` and `type` keys, set
301
+ `ids-and-types` for the related object.
302
+ This is particularly useful for polymorphic relationships where records don't share
303
+ the same table and the `id` is not enough information.
304
+ For example having a user that has many pets:
305
+ ```js
306
+ User = Model.extend({
307
+ name: attr('string'),
308
+ pets: hasMany('pet', { polymorphic: true })
309
+ });
310
+ Pet = Model.extend({
311
+ name: attr('string'),
312
+ });
313
+ Cat = Pet.extend({
314
+ // ...
315
+ });
316
+ Parrot = Pet.extend({
317
+ // ...
318
+ });
319
+ ```
320
+ ```app/serializers/user.js
321
+ import RESTSerializer, { EmbeddedRecordsMixin } from '@ember-data-mirror/serializer/rest';
322
+ export default class UserSerializer extends RESTSerializer.extend(EmbeddedRecordsMixin) {
323
+ attrs = {
324
+ pets: { serialize: 'ids-and-types', deserialize: 'records' }
325
+ }
326
+ }
327
+ ```
328
+ ```js
329
+ {
330
+ "user": {
331
+ "id": "1"
332
+ "name": "Bertin Osborne",
333
+ "pets": [
334
+ { "id": "1", "type": "Cat" },
335
+ { "id": "1", "type": "Parrot"}
336
+ ]
337
+ }
338
+ }
339
+ ```
340
+ @method serializeHasMany
341
+ @public
342
+ @param {Snapshot} snapshot
343
+ @param {Object} json
344
+ @param {Object} relationship
345
+ */
346
+ serializeHasMany(snapshot, json, relationship) {
347
+ const attr = relationship.name;
348
+ if (this.noSerializeOptionSpecified(attr)) {
349
+ this._super(snapshot, json, relationship);
350
+ return;
351
+ }
352
+ if (this.hasSerializeIdsOption(attr)) {
353
+ const schema = this.store.modelFor(snapshot.modelName);
354
+ let serializedKey = this._getMappedKey(relationship.name, schema);
355
+ if (serializedKey === relationship.name && this.keyForRelationship) {
356
+ serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
357
+ }
358
+ json[serializedKey] = snapshot.hasMany(attr, {
359
+ ids: true
360
+ });
361
+ } else if (this.hasSerializeRecordsOption(attr)) {
362
+ this._serializeEmbeddedHasMany(snapshot, json, relationship);
363
+ } else {
364
+ if (this.hasSerializeIdsAndTypesOption(attr)) {
365
+ this._serializeHasManyAsIdsAndTypes(snapshot, json, relationship);
366
+ }
367
+ }
368
+ },
369
+ /*
370
+ Serializes a hasMany relationship as an array of objects containing only `id` and `type`
371
+ keys.
372
+ This has its use case on polymorphic hasMany relationships where the server is not storing
373
+ all records in the same table using STI, and therefore the `id` is not enough information
374
+ TODO: Make the default in Ember-data 3.0??
375
+ */
376
+ _serializeHasManyAsIdsAndTypes(snapshot, json, relationship) {
377
+ const serializedKey = this.keyForAttribute(relationship.name, 'serialize');
378
+ const hasMany = snapshot.hasMany(relationship.name) || [];
379
+ json[serializedKey] = hasMany.map(function (recordSnapshot) {
380
+ //
381
+ // I'm sure I'm being utterly naive here. Probably id is a configurable property and
382
+ // type too, and the modelName has to be normalized somehow.
383
+ //
384
+ return {
385
+ id: recordSnapshot.id,
386
+ type: recordSnapshot.modelName
387
+ };
388
+ });
389
+ },
390
+ _serializeEmbeddedHasMany(snapshot, json, relationship) {
391
+ const schema = this.store.modelFor(snapshot.modelName);
392
+ let serializedKey = this._getMappedKey(relationship.name, schema);
393
+ if (serializedKey === relationship.name && this.keyForRelationship) {
394
+ serializedKey = this.keyForRelationship(relationship.name, relationship.kind, 'serialize');
395
+ }
396
+ warn(`The embedded relationship '${serializedKey}' is undefined for '${snapshot.modelName}' with id '${snapshot.id}'. Please include it in your original payload.`, typeof snapshot.hasMany(relationship.name) !== 'undefined', {
397
+ id: 'ds.serializer.embedded-relationship-undefined'
398
+ });
399
+ json[serializedKey] = this._generateSerializedHasMany(snapshot, relationship);
400
+ },
401
+ /*
402
+ Returns an array of embedded records serialized to JSON
403
+ */
404
+ _generateSerializedHasMany(snapshot, relationship) {
405
+ const hasMany = snapshot.hasMany(relationship.name) || [];
406
+ const ret = new Array(hasMany.length);
407
+ for (let i = 0; i < hasMany.length; i++) {
408
+ const embeddedSnapshot = hasMany[i];
409
+ const embeddedJson = embeddedSnapshot.serialize({
410
+ includeId: true
411
+ });
412
+ this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson);
413
+ ret[i] = embeddedJson;
414
+ }
415
+ return ret;
416
+ },
417
+ /**
418
+ When serializing an embedded record, modify the property (in the `JSON` payload)
419
+ that refers to the parent record (foreign key for the relationship).
420
+ Serializing a `belongsTo` relationship removes the property that refers to the
421
+ parent record
422
+ Serializing a `hasMany` relationship does not remove the property that refers to
423
+ the parent record.
424
+ @method removeEmbeddedForeignKey
425
+ @public
426
+ @param {Snapshot} snapshot
427
+ @param {Snapshot} embeddedSnapshot
428
+ @param {Object} relationship
429
+ @param {Object} json
430
+ */
431
+ removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json) {
432
+ if (relationship.kind === 'belongsTo') {
433
+ const schema = this.store.modelFor(snapshot.modelName);
434
+ const parentRecord = schema.inverseFor(relationship.name, this.store);
435
+ if (parentRecord) {
436
+ const name = parentRecord.name;
437
+ const embeddedSerializer = this.store.serializerFor(embeddedSnapshot.modelName);
438
+ const parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize');
439
+ if (parentKey) {
440
+ delete json[parentKey];
441
+ }
442
+ }
443
+ } /*else if (relationship.kind === 'hasMany') {
444
+ return;
445
+ }*/
446
+ },
447
+ // checks config for attrs option to embedded (always) - serialize and deserialize
448
+ hasEmbeddedAlwaysOption(attr) {
449
+ const option = this.attrsOption(attr);
450
+ return option && option.embedded === 'always';
451
+ },
452
+ // checks config for attrs option to serialize ids
453
+ hasSerializeRecordsOption(attr) {
454
+ const alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
455
+ const option = this.attrsOption(attr);
456
+ return alwaysEmbed || option && option.serialize === 'records';
457
+ },
458
+ // checks config for attrs option to serialize records
459
+ hasSerializeIdsOption(attr) {
460
+ const option = this.attrsOption(attr);
461
+ return option && (option.serialize === 'ids' || option.serialize === 'id');
462
+ },
463
+ // checks config for attrs option to serialize records as objects containing id and types
464
+ hasSerializeIdsAndTypesOption(attr) {
465
+ const option = this.attrsOption(attr);
466
+ return option && (option.serialize === 'ids-and-types' || option.serialize === 'id-and-type');
467
+ },
468
+ // checks config for attrs option to serialize records
469
+ noSerializeOptionSpecified(attr) {
470
+ const option = this.attrsOption(attr);
471
+ return !(option && (option.serialize || option.embedded));
472
+ },
473
+ // checks config for attrs option to deserialize records
474
+ // a defined option object for a resource is treated the same as
475
+ // `deserialize: 'records'`
476
+ hasDeserializeRecordsOption(attr) {
477
+ const alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
478
+ const option = this.attrsOption(attr);
479
+ return alwaysEmbed || option && option.deserialize === 'records';
480
+ },
481
+ attrsOption(attr) {
482
+ const attrs = this.attrs;
483
+ return attrs && (attrs[camelize(attr)] || attrs[attr]);
484
+ },
485
+ /**
486
+ @method _extractEmbeddedRecords
487
+ @private
488
+ */
489
+ _extractEmbeddedRecords(serializer, store, typeClass, partial) {
490
+ typeClass.eachRelationship((key, relationship) => {
491
+ if (serializer.hasDeserializeRecordsOption(key)) {
492
+ if (relationship.kind === 'hasMany') {
493
+ this._extractEmbeddedHasMany(store, key, partial, relationship);
494
+ }
495
+ if (relationship.kind === 'belongsTo') {
496
+ this._extractEmbeddedBelongsTo(store, key, partial, relationship);
497
+ }
498
+ }
499
+ });
500
+ return partial;
501
+ },
502
+ /**
503
+ @method _extractEmbeddedHasMany
504
+ @private
505
+ */
506
+ _extractEmbeddedHasMany(store, key, hash, relationshipMeta) {
507
+ const relationshipHash = hash.data?.relationships?.[key]?.data;
508
+ if (!relationshipHash) {
509
+ return;
510
+ }
511
+ const hasMany = new Array(relationshipHash.length);
512
+ for (let i = 0; i < relationshipHash.length; i++) {
513
+ const item = relationshipHash[i];
514
+ const {
515
+ data,
516
+ included
517
+ } = this._normalizeEmbeddedRelationship(store, relationshipMeta, item);
518
+ hash.included = hash.included || [];
519
+ hash.included.push(data);
520
+ if (included) {
521
+ hash.included = hash.included.concat(included);
522
+ }
523
+ hasMany[i] = {
524
+ id: data.id,
525
+ type: data.type
526
+ };
527
+ if (data.lid) {
528
+ hasMany[i].lid = data.lid;
529
+ }
530
+ }
531
+ const relationship = {
532
+ data: hasMany
533
+ };
534
+ hash.data.relationships[key] = relationship;
535
+ },
536
+ /**
537
+ @method _extractEmbeddedBelongsTo
538
+ @private
539
+ */
540
+ _extractEmbeddedBelongsTo(store, key, hash, relationshipMeta) {
541
+ const relationshipHash = hash.data?.relationships?.[key]?.data;
542
+ if (!relationshipHash) {
543
+ return;
544
+ }
545
+ const {
546
+ data,
547
+ included
548
+ } = this._normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash);
549
+ hash.included = hash.included || [];
550
+ hash.included.push(data);
551
+ if (included) {
552
+ hash.included = hash.included.concat(included);
553
+ }
554
+ const belongsTo = {
555
+ id: data.id,
556
+ type: data.type
557
+ };
558
+ const relationship = {
559
+ data: belongsTo
560
+ };
561
+ if (data.lid) {
562
+ belongsTo.lid = data.lid;
563
+ }
564
+ hash.data.relationships[key] = relationship;
565
+ },
566
+ /**
567
+ @method _normalizeEmbeddedRelationship
568
+ @private
569
+ */
570
+ _normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash) {
571
+ let modelName = relationshipMeta.type;
572
+ if (relationshipMeta.options.polymorphic) {
573
+ modelName = relationshipHash.type;
574
+ }
575
+ const modelClass = store.modelFor(modelName);
576
+ const serializer = store.serializerFor(modelName);
577
+ return serializer.normalize(modelClass, relationshipHash, null);
578
+ },
579
+ isEmbeddedRecordsMixin: true
580
+ });
581
+
582
+ /**
583
+ * @module @ember-data-mirror/serializer/rest
584
+ */
585
+ function makeArray(value) {
586
+ return Array.isArray(value) ? value : [value];
587
+ }
588
+
589
+ /**
590
+ * <blockquote style="margin: 1em; padding: .1em 1em .1em 1em; border-left: solid 1em #E34C32; background: #e0e0e0;">
591
+ <p>
592
+ ⚠️ <strong>This is LEGACY documentation</strong> for a feature that is no longer encouraged to be used.
593
+ If starting a new app or thinking of implementing a new adapter, consider writing a
594
+ <a href="/ember-data/release/classes/%3CInterface%3E%20Handler">Handler</a> instead to be used with the <a href="https://github.com/emberjs/data/tree/main/packages/request#readme">RequestManager</a>
595
+ </p>
596
+ </blockquote>
597
+
598
+ Normally, applications will use the `RESTSerializer` by implementing
599
+ the `normalize` method.
600
+
601
+ This allows you to do whatever kind of munging you need and is
602
+ especially useful if your server is inconsistent and you need to
603
+ do munging differently for many different kinds of responses.
604
+
605
+ See the `normalize` documentation for more information.
606
+
607
+ ## Across the Board Normalization
608
+
609
+ There are also a number of hooks that you might find useful to define
610
+ across-the-board rules for your payload. These rules will be useful
611
+ if your server is consistent, or if you're building an adapter for
612
+ an infrastructure service, like Firebase, and want to encode service
613
+ conventions.
614
+
615
+ For example, if all of your keys are underscored and all-caps, but
616
+ otherwise consistent with the names you use in your models, you
617
+ can implement across-the-board rules for how to convert an attribute
618
+ name in your model to a key in your JSON.
619
+
620
+ ```app/serializers/application.js
621
+ import RESTSerializer from '@ember-data-mirror/serializer/rest';
622
+ import { underscore } from '<app-name>/utils/string-utils';
623
+
624
+ export default class ApplicationSerializer extends RESTSerializer {
625
+ keyForAttribute(attr, method) {
626
+ return underscore(attr).toUpperCase();
627
+ }
628
+ }
629
+ ```
630
+
631
+ You can also implement `keyForRelationship`, which takes the name
632
+ of the relationship as the first parameter, the kind of
633
+ relationship (`hasMany` or `belongsTo`) as the second parameter, and
634
+ the method (`serialize` or `deserialize`) as the third parameter.
635
+
636
+ @class RESTSerializer
637
+ @main @ember-data-mirror/serializer/rest
638
+ @public
639
+ @extends JSONSerializer
640
+ */
641
+ const RESTSerializer = JSONSerializer.extend({
642
+ /**
643
+ `keyForPolymorphicType` can be used to define a custom key when
644
+ serializing and deserializing a polymorphic type. By default, the
645
+ returned key is `${key}Type`.
646
+ Example
647
+ ```app/serializers/post.js
648
+ import RESTSerializer from '@ember-data-mirror/serializer/rest';
649
+ export default class ApplicationSerializer extends RESTSerializer {
650
+ keyForPolymorphicType(key, relationship) {
651
+ let relationshipKey = this.keyForRelationship(key);
652
+ return 'type-' + relationshipKey;
653
+ }
654
+ }
655
+ ```
656
+ @method keyForPolymorphicType
657
+ @public
658
+ @param {String} key
659
+ @param {String} typeClass
660
+ @param {String} method
661
+ @return {String} normalized key
662
+ */
663
+ keyForPolymorphicType(key, typeClass, method) {
664
+ const relationshipKey = this.keyForRelationship(key);
665
+ return `${relationshipKey}Type`;
666
+ },
667
+ /**
668
+ Normalizes a part of the JSON payload returned by
669
+ the server. You should override this method, munge the hash
670
+ and call super if you have generic normalization to do.
671
+ It takes the type of the record that is being normalized
672
+ (as a Model class), the property where the hash was
673
+ originally found, and the hash to normalize.
674
+ For example, if you have a payload that looks like this:
675
+ ```js
676
+ {
677
+ "post": {
678
+ "id": 1,
679
+ "title": "Rails is omakase",
680
+ "comments": [ 1, 2 ]
681
+ },
682
+ "comments": [{
683
+ "id": 1,
684
+ "body": "FIRST"
685
+ }, {
686
+ "id": 2,
687
+ "body": "Rails is unagi"
688
+ }]
689
+ }
690
+ ```
691
+ The `normalize` method will be called three times:
692
+ * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }`
693
+ * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }`
694
+ * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }`
695
+ You can use this method, for example, to normalize underscored keys to camelized
696
+ or other general-purpose normalizations. You will only need to implement
697
+ `normalize` and manipulate the payload as desired.
698
+ For example, if the `IDs` under `"comments"` are provided as `_id` instead of
699
+ `id`, you can specify how to normalize just the comments:
700
+ ```app/serializers/post.js
701
+ import RESTSerializer from '@ember-data-mirror/serializer/rest';
702
+ export default class ApplicationSerializer extends RESTSerializer {
703
+ normalize(model, hash, prop) {
704
+ if (prop === 'comments') {
705
+ hash.id = hash._id;
706
+ delete hash._id;
707
+ }
708
+ return super.normalize(...arguments);
709
+ }
710
+ }
711
+ ```
712
+ On each call to the `normalize` method, the third parameter (`prop`) is always
713
+ one of the keys that were in the original payload or in the result of another
714
+ normalization as `normalizeResponse`.
715
+ @method normalize
716
+ @public
717
+ @param {Model} modelClass
718
+ @param {Object} resourceHash
719
+ @param {String} prop
720
+ @return {Object}
721
+ */
722
+
723
+ /**
724
+ Normalizes an array of resource payloads and returns a JSON-API Document
725
+ with primary data and, if any, included data as `{ data, included }`.
726
+ @method _normalizeArray
727
+ @param {Store} store
728
+ @param {String} modelName
729
+ @param {Object} arrayHash
730
+ @param {String} prop
731
+ @return {Object}
732
+ @private
733
+ */
734
+ _normalizeArray(store, modelName, arrayHash, prop) {
735
+ const documentHash = {
736
+ data: [],
737
+ included: []
738
+ };
739
+ const modelClass = store.modelFor(modelName);
740
+ const serializer = store.serializerFor(modelName);
741
+ makeArray(arrayHash).forEach(hash => {
742
+ const {
743
+ data,
744
+ included
745
+ } = this._normalizePolymorphicRecord(store, hash, prop, modelClass, serializer);
746
+ documentHash.data.push(data);
747
+ if (included) {
748
+ documentHash.included = documentHash.included.concat(included);
749
+ }
750
+ });
751
+ return documentHash;
752
+ },
753
+ _normalizePolymorphicRecord(store, hash, prop, primaryModelClass, primarySerializer) {
754
+ let serializer = primarySerializer;
755
+ let modelClass = primaryModelClass;
756
+ const primaryHasTypeAttribute = primaryModelClass.fields.has('type');
757
+ if (!primaryHasTypeAttribute && hash.type) {
758
+ // Support polymorphic records in async relationships
759
+ const type = this.modelNameFromPayloadKey(hash.type);
760
+ if (store.schema.hasResource({
761
+ type
762
+ })) {
763
+ serializer = store.serializerFor(type);
764
+ modelClass = store.modelFor(type);
765
+ }
766
+ }
767
+ return serializer.normalize(modelClass, hash, prop);
768
+ },
769
+ /**
770
+ @method _normalizeResponse
771
+ @param {Store} store
772
+ @param {Model} primaryModelClass
773
+ @param {Object} payload
774
+ @param {String|Number} id
775
+ @param {String} requestType
776
+ @param {Boolean} isSingle
777
+ @return {Object} JSON-API Document
778
+ @private
779
+ */
780
+ _normalizeResponse(store, primaryModelClass, payload, id, requestType, isSingle) {
781
+ const documentHash = {
782
+ data: null,
783
+ included: []
784
+ };
785
+ const meta = this.extractMeta(store, primaryModelClass, payload);
786
+ if (meta) {
787
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
788
+ if (!test) {
789
+ throw new Error('The `meta` returned from `extractMeta` has to be an object, not "' + typeof meta + '".');
790
+ }
791
+ })(typeof meta === 'object') : {};
792
+ documentHash.meta = meta;
793
+ }
794
+ const keys = Object.keys(payload);
795
+ for (var i = 0, length = keys.length; i < length; i++) {
796
+ var prop = keys[i];
797
+ var modelName = prop;
798
+ var forcedSecondary = false;
799
+
800
+ /*
801
+ If you want to provide sideloaded records of the same type that the
802
+ primary data you can do that by prefixing the key with `_`.
803
+ Example
804
+ ```
805
+ {
806
+ users: [
807
+ { id: 1, title: 'Tom', manager: 3 },
808
+ { id: 2, title: 'Yehuda', manager: 3 }
809
+ ],
810
+ _users: [
811
+ { id: 3, title: 'Tomster' }
812
+ ]
813
+ }
814
+ ```
815
+ This forces `_users` to be added to `included` instead of `data`.
816
+ */
817
+ if (prop.charAt(0) === '_') {
818
+ forcedSecondary = true;
819
+ modelName = prop.substr(1);
820
+ }
821
+ const type = this.modelNameFromPayloadKey(modelName);
822
+ if (!store.schema.hasResource({
823
+ type
824
+ })) {
825
+ warn(this.warnMessageNoModelForKey(modelName, type), false, {
826
+ id: 'ds.serializer.model-for-key-missing'
827
+ });
828
+ continue;
829
+ }
830
+ var isPrimary = !forcedSecondary && this.isPrimaryType(store, type, primaryModelClass);
831
+ var value = payload[prop];
832
+ if (value === null) {
833
+ continue;
834
+ }
835
+ macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
836
+ if (!test) {
837
+ throw new Error('The adapter returned an array for the primary data of a `queryRecord` response. `queryRecord` should return a single record.');
838
+ }
839
+ })(!(requestType === 'queryRecord' && isPrimary && Array.isArray(value))) : {};
840
+
841
+ /*
842
+ Support primary data as an object instead of an array.
843
+ Example
844
+ ```
845
+ {
846
+ user: { id: 1, title: 'Tom', manager: 3 }
847
+ }
848
+ ```
849
+ */
850
+ if (isPrimary && !Array.isArray(value)) {
851
+ const {
852
+ data,
853
+ included
854
+ } = this._normalizePolymorphicRecord(store, value, prop, primaryModelClass, this);
855
+ documentHash.data = data;
856
+ if (included) {
857
+ documentHash.included = documentHash.included.concat(included);
858
+ }
859
+ continue;
860
+ }
861
+ const {
862
+ data,
863
+ included
864
+ } = this._normalizeArray(store, type, value, prop);
865
+ if (included) {
866
+ documentHash.included = documentHash.included.concat(included);
867
+ }
868
+ if (isSingle) {
869
+ data.forEach(resource => {
870
+ /*
871
+ Figures out if this is the primary record or not.
872
+ It's either:
873
+ 1. The record with the same ID as the original request
874
+ 2. If it's a newly created record without an ID, the first record
875
+ in the array
876
+ */
877
+ const isUpdatedRecord = isPrimary && coerceId(resource.id) === id;
878
+ const isFirstCreatedRecord = isPrimary && !id && !documentHash.data;
879
+ if (isFirstCreatedRecord || isUpdatedRecord) {
880
+ documentHash.data = resource;
881
+ } else {
882
+ documentHash.included.push(resource);
883
+ }
884
+ });
885
+ } else {
886
+ if (isPrimary) {
887
+ documentHash.data = data;
888
+ } else {
889
+ if (data) {
890
+ documentHash.included = documentHash.included.concat(data);
891
+ }
892
+ }
893
+ }
894
+ }
895
+ return documentHash;
896
+ },
897
+ isPrimaryType(store, modelName, primaryModelClass) {
898
+ return dasherize(modelName) === primaryModelClass.modelName;
899
+ },
900
+ /**
901
+ This method allows you to push a payload containing top-level
902
+ collections of records organized per type.
903
+ ```js
904
+ {
905
+ "posts": [{
906
+ "id": "1",
907
+ "title": "Rails is omakase",
908
+ "author", "1",
909
+ "comments": [ "1" ]
910
+ }],
911
+ "comments": [{
912
+ "id": "1",
913
+ "body": "FIRST"
914
+ }],
915
+ "users": [{
916
+ "id": "1",
917
+ "name": "@d2h"
918
+ }]
919
+ }
920
+ ```
921
+ It will first normalize the payload, so you can use this to push
922
+ in data streaming in from your server structured the same way
923
+ that fetches and saves are structured.
924
+ @method pushPayload
925
+ @public
926
+ @param {Store} store
927
+ @param {Object} payload
928
+ */
929
+ pushPayload(store, payload) {
930
+ const documentHash = {
931
+ data: [],
932
+ included: []
933
+ };
934
+ for (const prop in payload) {
935
+ const type = this.modelNameFromPayloadKey(prop);
936
+ if (!store.schema.hasResource({
937
+ type
938
+ })) {
939
+ warn(this.warnMessageNoModelForKey(prop, type), false, {
940
+ id: 'ds.serializer.model-for-key-missing'
941
+ });
942
+ continue;
943
+ }
944
+ const ModelSchema = store.modelFor(type);
945
+ const typeSerializer = store.serializerFor(ModelSchema.modelName);
946
+ makeArray(payload[prop]).forEach(hash => {
947
+ const {
948
+ data,
949
+ included
950
+ } = typeSerializer.normalize(ModelSchema, hash, prop);
951
+ documentHash.data.push(data);
952
+ if (included) {
953
+ documentHash.included = documentHash.included.concat(included);
954
+ }
955
+ });
956
+ }
957
+ store.push(documentHash);
958
+ },
959
+ /**
960
+ This method is used to convert each JSON root key in the payload
961
+ into a modelName that it can use to look up the appropriate model for
962
+ that part of the payload.
963
+ For example, your server may send a model name that does not correspond with
964
+ the name of the model in your app. Let's take a look at an example model,
965
+ and an example payload:
966
+ ```app/models/post.js
967
+ import Model from '@ember-data-mirror/model';
968
+ export default class Post extends Model {}
969
+ ```
970
+ ```javascript
971
+ {
972
+ "blog/post": {
973
+ "id": "1
974
+ }
975
+ }
976
+ ```
977
+ Ember Data is going to normalize the payload's root key for the modelName. As a result,
978
+ it will try to look up the "blog/post" model. Since we don't have a model called "blog/post"
979
+ (or a file called app/models/blog/post.js in ember-cli), Ember Data will throw an error
980
+ because it cannot find the "blog/post" model.
981
+ Since we want to remove this namespace, we can define a serializer for the application that will
982
+ remove "blog/" from the payload key whenver it's encountered by Ember Data:
983
+ ```app/serializers/application.js
984
+ import RESTSerializer from '@ember-data-mirror/serializer/rest';
985
+ export default class ApplicationSerializer extends RESTSerializer {
986
+ modelNameFromPayloadKey(payloadKey) {
987
+ if (payloadKey === 'blog/post') {
988
+ return super.modelNameFromPayloadKey(payloadKey.replace('blog/', ''));
989
+ } else {
990
+ return super.modelNameFromPayloadKey(payloadKey);
991
+ }
992
+ }
993
+ }
994
+ ```
995
+ After refreshing, Ember Data will appropriately look up the "post" model.
996
+ By default the modelName for a model is its
997
+ name in dasherized form. This means that a payload key like "blogPost" would be
998
+ normalized to "blog-post" when Ember Data looks up the model. Usually, Ember Data
999
+ can use the correct inflection to do this for you. Most of the time, you won't
1000
+ need to override `modelNameFromPayloadKey` for this purpose.
1001
+ @method modelNameFromPayloadKey
1002
+ @public
1003
+ @param {String} key
1004
+ @return {String} the model's modelName
1005
+ */
1006
+ modelNameFromPayloadKey(key) {
1007
+ return dasherize(singularize(key));
1008
+ },
1009
+ // SERIALIZE
1010
+
1011
+ /**
1012
+ Called when a record is saved in order to convert the
1013
+ record into JSON.
1014
+ By default, it creates a JSON object with a key for
1015
+ each attribute and belongsTo relationship.
1016
+ For example, consider this model:
1017
+ ```app/models/comment.js
1018
+ import Model, { attr, belongsTo } from '@ember-data-mirror/model';
1019
+ export default class Comment extends Model {
1020
+ @attr title
1021
+ @attr body
1022
+ @belongsTo('user') author
1023
+ }
1024
+ ```
1025
+ The default serialization would create a JSON object like:
1026
+ ```js
1027
+ {
1028
+ "title": "Rails is unagi",
1029
+ "body": "Rails? Omakase? O_O",
1030
+ "author": 12
1031
+ }
1032
+ ```
1033
+ By default, attributes are passed through as-is, unless
1034
+ you specified an attribute type (`attr('date')`). If
1035
+ you specify a transform, the JavaScript value will be
1036
+ serialized when inserted into the JSON hash.
1037
+ By default, belongs-to relationships are converted into
1038
+ IDs when inserted into the JSON hash.
1039
+ ## IDs
1040
+ `serialize` takes an options hash with a single option:
1041
+ `includeId`. If this option is `true`, `serialize` will,
1042
+ by default include the ID in the JSON object it builds.
1043
+ The adapter passes in `includeId: true` when serializing
1044
+ a record for `createRecord`, but not for `updateRecord`.
1045
+ ## Customization
1046
+ Your server may expect a different JSON format than the
1047
+ built-in serialization format.
1048
+ In that case, you can implement `serialize` yourself and
1049
+ return a JSON hash of your choosing.
1050
+ ```app/serializers/post.js
1051
+ import RESTSerializer from '@ember-data-mirror/serializer/rest';
1052
+ export default class ApplicationSerializer extends RESTSerializer {
1053
+ serialize(snapshot, options) {
1054
+ let json = {
1055
+ POST_TTL: snapshot.attr('title'),
1056
+ POST_BDY: snapshot.attr('body'),
1057
+ POST_CMS: snapshot.hasMany('comments', { ids: true })
1058
+ };
1059
+ if (options.includeId) {
1060
+ json.POST_ID_ = snapshot.id;
1061
+ }
1062
+ return json;
1063
+ }
1064
+ }
1065
+ ```
1066
+ ## Customizing an App-Wide Serializer
1067
+ If you want to define a serializer for your entire
1068
+ application, you'll probably want to use `eachAttribute`
1069
+ and `eachRelationship` on the record.
1070
+ ```app/serializers/application.js
1071
+ import RESTSerializer from '@ember-data-mirror/serializer/rest';
1072
+ import { pluralize } from '<app-name>/utils/string-utils';
1073
+ export default class ApplicationSerializer extends RESTSerializer {
1074
+ serialize(snapshot, options) {
1075
+ let json = {};
1076
+ snapshot.eachAttribute(function(name) {
1077
+ json[serverAttributeName(name)] = snapshot.attr(name);
1078
+ });
1079
+ snapshot.eachRelationship(function(name, relationship) {
1080
+ if (relationship.kind === 'hasMany') {
1081
+ json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true });
1082
+ }
1083
+ });
1084
+ if (options.includeId) {
1085
+ json.ID_ = snapshot.id;
1086
+ }
1087
+ return json;
1088
+ }
1089
+ }
1090
+ function serverAttributeName(attribute) {
1091
+ return attribute.underscore().toUpperCase();
1092
+ }
1093
+ function serverHasManyName(name) {
1094
+ return serverAttributeName(singularize(name)) + "_IDS";
1095
+ }
1096
+ ```
1097
+ This serializer will generate JSON that looks like this:
1098
+ ```js
1099
+ {
1100
+ "TITLE": "Rails is omakase",
1101
+ "BODY": "Yep. Omakase.",
1102
+ "COMMENT_IDS": [ 1, 2, 3 ]
1103
+ }
1104
+ ```
1105
+ ## Tweaking the Default JSON
1106
+ If you just want to do some small tweaks on the default JSON,
1107
+ you can call super first and make the tweaks on the returned
1108
+ JSON.
1109
+ ```app/serializers/post.js
1110
+ import RESTSerializer from '@ember-data-mirror/serializer/rest';
1111
+ export default class ApplicationSerializer extends RESTSerializer {
1112
+ serialize(snapshot, options) {
1113
+ let json = super.serialize(snapshot, options);
1114
+ json.subject = json.title;
1115
+ delete json.title;
1116
+ return json;
1117
+ }
1118
+ }
1119
+ ```
1120
+ @method serialize
1121
+ @public
1122
+ @param {Snapshot} snapshot
1123
+ @param {Object} options
1124
+ @return {Object} json
1125
+ */
1126
+ serialize(snapshot, options) {
1127
+ return this._super(...arguments);
1128
+ },
1129
+ /**
1130
+ You can use this method to customize the root keys serialized into the JSON.
1131
+ The hash property should be modified by reference (possibly using something like _.extend)
1132
+ By default the REST Serializer sends the modelName of a model, which is a camelized
1133
+ version of the name.
1134
+ For example, your server may expect underscored root objects.
1135
+ ```app/serializers/application.js
1136
+ import RESTSerializer from '@ember-data-mirror/serializer/rest';
1137
+ import { decamelize } from '<app-name>/utils/string-utils';
1138
+ export default class ApplicationSerializer extends RESTSerializer {
1139
+ serializeIntoHash(data, type, record, options) {
1140
+ let root = decamelize(type.modelName);
1141
+ data[root] = this.serialize(record, options);
1142
+ }
1143
+ }
1144
+ ```
1145
+ @method serializeIntoHash
1146
+ @public
1147
+ @param {Object} hash
1148
+ @param {Model} typeClass
1149
+ @param {Snapshot} snapshot
1150
+ @param {Object} options
1151
+ */
1152
+ serializeIntoHash(hash, typeClass, snapshot, options) {
1153
+ const normalizedRootKey = this.payloadKeyFromModelName(typeClass.modelName);
1154
+ hash[normalizedRootKey] = this.serialize(snapshot, options);
1155
+ },
1156
+ /**
1157
+ You can use `payloadKeyFromModelName` to override the root key for an outgoing
1158
+ request. By default, the RESTSerializer returns a camelized version of the
1159
+ model's name.
1160
+ For a model called TacoParty, its `modelName` would be the string `taco-party`. The RESTSerializer
1161
+ will send it to the server with `tacoParty` as the root key in the JSON payload:
1162
+ ```js
1163
+ {
1164
+ "tacoParty": {
1165
+ "id": "1",
1166
+ "location": "Matthew Beale's House"
1167
+ }
1168
+ }
1169
+ ```
1170
+ For example, your server may expect dasherized root objects:
1171
+ ```app/serializers/application.js
1172
+ import RESTSerializer from '@ember-data-mirror/serializer/rest';
1173
+ import { dasherize } from '<app-name>/utils/string-utils';
1174
+ export default class ApplicationSerializer extends RESTSerializer {
1175
+ payloadKeyFromModelName(modelName) {
1176
+ return dasherize(modelName);
1177
+ }
1178
+ }
1179
+ ```
1180
+ Given a `TacoParty` model, calling `save` on it would produce an outgoing
1181
+ request like:
1182
+ ```js
1183
+ {
1184
+ "taco-party": {
1185
+ "id": "1",
1186
+ "location": "Matthew Beale's House"
1187
+ }
1188
+ }
1189
+ ```
1190
+ @method payloadKeyFromModelName
1191
+ @public
1192
+ @param {String} modelName
1193
+ @return {String}
1194
+ */
1195
+ payloadKeyFromModelName(modelName) {
1196
+ return camelize(modelName);
1197
+ },
1198
+ /**
1199
+ You can use this method to customize how polymorphic objects are serialized.
1200
+ By default the REST Serializer creates the key by appending `Type` to
1201
+ the attribute and value from the model's camelcased model name.
1202
+ @method serializePolymorphicType
1203
+ @public
1204
+ @param {Snapshot} snapshot
1205
+ @param {Object} json
1206
+ @param {Object} relationship
1207
+ */
1208
+ serializePolymorphicType(snapshot, json, relationship) {
1209
+ const name = relationship.name;
1210
+ const typeKey = this.keyForPolymorphicType(name, relationship.type, 'serialize');
1211
+ const belongsTo = snapshot.belongsTo(name);
1212
+ if (!belongsTo) {
1213
+ json[typeKey] = null;
1214
+ } else {
1215
+ json[typeKey] = camelize(belongsTo.modelName);
1216
+ }
1217
+ },
1218
+ /**
1219
+ You can use this method to customize how a polymorphic relationship should
1220
+ be extracted.
1221
+ @method extractPolymorphicRelationship
1222
+ @public
1223
+ @param {Object} relationshipType
1224
+ @param {Object} relationshipHash
1225
+ @param {Object} relationshipOptions
1226
+ @return {Object}
1227
+ */
1228
+ extractPolymorphicRelationship(relationshipType, relationshipHash, relationshipOptions) {
1229
+ const {
1230
+ key,
1231
+ resourceHash,
1232
+ relationshipMeta
1233
+ } = relationshipOptions;
1234
+
1235
+ // A polymorphic belongsTo relationship can be present in the payload
1236
+ // either in the form where the `id` and the `type` are given:
1237
+ //
1238
+ // {
1239
+ // message: { id: 1, type: 'post' }
1240
+ // }
1241
+ //
1242
+ // or by the `id` and a `<relationship>Type` attribute:
1243
+ //
1244
+ // {
1245
+ // message: 1,
1246
+ // messageType: 'post'
1247
+ // }
1248
+ //
1249
+ // The next code checks if the latter case is present and returns the
1250
+ // corresponding JSON-API representation. The former case is handled within
1251
+ // the base class JSONSerializer.
1252
+ const isPolymorphic = relationshipMeta.options.polymorphic;
1253
+ const typeProperty = this.keyForPolymorphicType(key, relationshipType, 'deserialize');
1254
+ if (isPolymorphic && resourceHash[typeProperty] !== undefined && typeof relationshipHash !== 'object') {
1255
+ const type = this.modelNameFromPayloadKey(resourceHash[typeProperty]);
1256
+ return {
1257
+ id: coerceId(relationshipHash),
1258
+ type: type
1259
+ };
1260
+ }
1261
+ return this._super(...arguments);
1262
+ }
1263
+ });
1264
+ if (macroCondition(getGlobalConfig().WarpDrive.env.DEBUG)) {
1265
+ RESTSerializer.reopen({
1266
+ warnMessageNoModelForKey(prop, typeKey) {
1267
+ return 'Encountered "' + prop + '" in payload, but no model was found for model name "' + typeKey + '" (resolved model name using ' + this.constructor.toString() + '.modelNameFromPayloadKey("' + prop + '"))';
1268
+ }
1269
+ });
1270
+ }
1271
+ export { EmbeddedRecordsMixin, RESTSerializer as default };