@ember-data-mirror/serializer 5.6.0-alpha.5 → 5.6.0-beta.1

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