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

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