-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathjson.js
1578 lines (1317 loc) · 45.2 KB
/
json.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module @ember-data/serializer/json
*/
import { getOwner } from '@ember/application';
import { assert, warn } from '@ember/debug';
import { get } from '@ember/object';
import { isNone, typeOf } from '@ember/utils';
import Serializer from '@ember-data/serializer';
import { normalizeModelName } from '@ember-data/store';
import { coerceId, errorsArrayToHash } from '@ember-data/store/-private';
import { modelHasAttributeOrRelationshipNamedType } from './-private';
/**
Ember Data 2.0 Serializer:
In Ember Data a Serializer is used to serialize and deserialize
records when they are transferred in and out of an external source.
This process involves normalizing property names, transforming
attribute values and serializing relationships.
By default, Ember Data uses and recommends the `JSONAPISerializer`.
`JSONSerializer` is useful for simpler or legacy backends that may
not support the http://jsonapi.org/ spec.
For example, given the following `User` model and JSON payload:
```app/models/user.js
import Model, { attr, belongsTo, hasMany } from '@ember-data/model';
export default class UserModel extends Model {
@hasMany('user') friends;
@belongsTo('location') house;
@attr('string') name;
}
```
```js
{
id: 1,
name: 'Sebastian',
friends: [3, 4],
links: {
house: '/houses/lefkada'
}
}
```
`JSONSerializer` will normalize the JSON payload to the JSON API format that the
Ember Data store expects.
You can customize how JSONSerializer processes its payload by passing options in
the `attrs` hash or by subclassing the `JSONSerializer` and overriding hooks:
- To customize how a single record is normalized, use the `normalize` hook.
- To customize how `JSONSerializer` normalizes the whole server response, use the
`normalizeResponse` hook.
- To customize how `JSONSerializer` normalizes a specific response from the server,
use one of the many specific `normalizeResponse` hooks.
- To customize how `JSONSerializer` normalizes your id, attributes or relationships,
use the `extractId`, `extractAttributes` and `extractRelationships` hooks.
The `JSONSerializer` normalization process follows these steps:
1. `normalizeResponse`
- entry method to the serializer.
2. `normalizeCreateRecordResponse`
- a `normalizeResponse` for a specific operation is called.
3. `normalizeSingleResponse`|`normalizeArrayResponse`
- for methods like `createRecord` we expect a single record back, while for methods like `findAll` we expect multiple records back.
4. `normalize`
- `normalizeArrayResponse` iterates and calls `normalize` for each of its records while `normalizeSingle`
calls it once. This is the method you most likely want to subclass.
5. `extractId` | `extractAttributes` | `extractRelationships`
- `normalize` delegates to these methods to
turn the record payload into the JSON API format.
@main @ember-data/serializer/json
@class JSONSerializer
@public
@extends Serializer
*/
const JSONSerializer = Serializer.extend({
/**
The `primaryKey` is used when serializing and deserializing
data. Ember Data always uses the `id` property to store the id of
the record. The external source may not always follow this
convention. In these cases it is useful to override the
`primaryKey` property to match the `primaryKey` of your external
store.
Example
```app/serializers/application.js
import JSONSerializer from '@ember-data/serializer/json';
export default class ApplicationSerializer extends JSONSerializer {
primaryKey = '_id'
}
```
@property primaryKey
@type {String}
@public
@default 'id'
*/
primaryKey: 'id',
/**
The `attrs` object can be used to declare a simple mapping between
property names on `Model` records and payload keys in the
serialized JSON object representing the record. An object with the
property `key` can also be used to designate the attribute's key on
the response payload.
Example
```app/models/person.js
import Model, { attr } from '@ember-data/model';
export default class PersonModel extends Model {
@attr('string') firstName;
@attr('string') lastName;
@attr('string') occupation;
@attr('boolean') admin;
}
```
```app/serializers/person.js
import JSONSerializer from '@ember-data/serializer/json';
export default class PersonSerializer extends JSONSerializer {
attrs = {
admin: 'is_admin',
occupation: { key: 'career' }
}
}
```
You can also remove attributes and relationships by setting the `serialize`
key to `false` in your mapping object.
Example
```app/serializers/person.js
import JSONSerializer from '@ember-data/serializer/json';
export default class PostSerializer extends JSONSerializer {
attrs = {
admin: { serialize: false },
occupation: { key: 'career' }
}
}
```
When serialized:
```javascript
{
"firstName": "Harry",
"lastName": "Houdini",
"career": "magician"
}
```
Note that the `admin` is now not included in the payload.
Setting `serialize` to `true` enforces serialization for hasMany
relationships even if it's neither a many-to-many nor many-to-none
relationship.
@property attrs
@public
@type {Object}
*/
mergedProperties: ['attrs'],
/**
Given a subclass of `Model` and a JSON object this method will
iterate through each attribute of the `Model` and invoke the
`Transform#deserialize` method on the matching property of the
JSON object. This method is typically called after the
serializer's `normalize` method.
@method applyTransforms
@private
@param {Model} typeClass
@param {Object} data The data to transform
@return {Object} data The transformed data object
*/
applyTransforms(typeClass, data) {
let attributes = get(typeClass, 'attributes');
typeClass.eachTransformedAttribute((key, typeClass) => {
if (data[key] === undefined) {
return;
}
let transform = this.transformFor(typeClass);
let transformMeta = attributes.get(key);
data[key] = transform.deserialize(data[key], transformMeta.options);
});
return data;
},
/**
The `normalizeResponse` method is used to normalize a payload from the
server to a JSON-API Document.
http://jsonapi.org/format/#document-structure
This method delegates to a more specific normalize method based on
the `requestType`.
To override this method with a custom one, make sure to call
`return super.normalizeResponse(store, primaryModelClass, payload, id, requestType)` with your
pre-processed data.
Here's an example of using `normalizeResponse` manually:
```javascript
socket.on('message', function(message) {
let data = message.data;
let modelClass = store.modelFor(data.modelName);
let serializer = store.serializerFor(data.modelName);
let normalized = serializer.normalizeSingleResponse(store, modelClass, data, data.id);
store.push(normalized);
});
```
@since 1.13.0
@method normalizeResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
switch (requestType) {
case 'findRecord':
return this.normalizeFindRecordResponse(...arguments);
case 'queryRecord':
return this.normalizeQueryRecordResponse(...arguments);
case 'findAll':
return this.normalizeFindAllResponse(...arguments);
case 'findBelongsTo':
return this.normalizeFindBelongsToResponse(...arguments);
case 'findHasMany':
return this.normalizeFindHasManyResponse(...arguments);
case 'findMany':
return this.normalizeFindManyResponse(...arguments);
case 'query':
return this.normalizeQueryResponse(...arguments);
case 'createRecord':
return this.normalizeCreateRecordResponse(...arguments);
case 'deleteRecord':
return this.normalizeDeleteRecordResponse(...arguments);
case 'updateRecord':
return this.normalizeUpdateRecordResponse(...arguments);
}
},
/**
Called by the default normalizeResponse implementation when the
type of request is `findRecord`
@since 1.13.0
@method normalizeFindRecordResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeFindRecordResponse(store, primaryModelClass, payload, id, requestType) {
return this.normalizeSingleResponse(...arguments);
},
/**
Called by the default normalizeResponse implementation when the
type of request is `queryRecord`
@since 1.13.0
@method normalizeQueryRecordResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeQueryRecordResponse(store, primaryModelClass, payload, id, requestType) {
return this.normalizeSingleResponse(...arguments);
},
/**
Called by the default normalizeResponse implementation when the
type of request is `findAll`
@since 1.13.0
@method normalizeFindAllResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeFindAllResponse(store, primaryModelClass, payload, id, requestType) {
return this.normalizeArrayResponse(...arguments);
},
/**
Called by the default normalizeResponse implementation when the
type of request is `findBelongsTo`
@since 1.13.0
@method normalizeFindBelongsToResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeFindBelongsToResponse(store, primaryModelClass, payload, id, requestType) {
return this.normalizeSingleResponse(...arguments);
},
/**
Called by the default normalizeResponse implementation when the
type of request is `findHasMany`
@since 1.13.0
@method normalizeFindHasManyResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeFindHasManyResponse(store, primaryModelClass, payload, id, requestType) {
return this.normalizeArrayResponse(...arguments);
},
/**
Called by the default normalizeResponse implementation when the
type of request is `findMany`
@since 1.13.0
@method normalizeFindManyResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeFindManyResponse(store, primaryModelClass, payload, id, requestType) {
return this.normalizeArrayResponse(...arguments);
},
/**
Called by the default normalizeResponse implementation when the
type of request is `query`
@since 1.13.0
@method normalizeQueryResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) {
return this.normalizeArrayResponse(...arguments);
},
/**
Called by the default normalizeResponse implementation when the
type of request is `createRecord`
@since 1.13.0
@method normalizeCreateRecordResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeCreateRecordResponse(store, primaryModelClass, payload, id, requestType) {
return this.normalizeSaveResponse(...arguments);
},
/**
Called by the default normalizeResponse implementation when the
type of request is `deleteRecord`
@since 1.13.0
@method normalizeDeleteRecordResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeDeleteRecordResponse(store, primaryModelClass, payload, id, requestType) {
return this.normalizeSaveResponse(...arguments);
},
/**
Called by the default normalizeResponse implementation when the
type of request is `updateRecord`
@since 1.13.0
@method normalizeUpdateRecordResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeUpdateRecordResponse(store, primaryModelClass, payload, id, requestType) {
return this.normalizeSaveResponse(...arguments);
},
/**
normalizeUpdateRecordResponse, normalizeCreateRecordResponse and
normalizeDeleteRecordResponse delegate to this method by default.
@since 1.13.0
@method normalizeSaveResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeSaveResponse(store, primaryModelClass, payload, id, requestType) {
return this.normalizeSingleResponse(...arguments);
},
/**
normalizeQueryResponse and normalizeFindRecordResponse delegate to this
method by default.
@since 1.13.0
@method normalizeSingleResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeSingleResponse(store, primaryModelClass, payload, id, requestType) {
return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, true);
},
/**
normalizeQueryResponse, normalizeFindManyResponse, and normalizeFindHasManyResponse delegate
to this method by default.
@since 1.13.0
@method normalizeArrayResponse
@public
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@return {Object} JSON-API Document
*/
normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) {
return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, false);
},
/**
@method _normalizeResponse
@param {Store} store
@param {Model} primaryModelClass
@param {Object} payload
@param {String|Number} id
@param {String} requestType
@param {Boolean} isSingle
@return {Object} JSON-API Document
@private
*/
_normalizeResponse(store, primaryModelClass, payload, id, requestType, isSingle) {
let documentHash = {
data: null,
included: [],
};
let meta = this.extractMeta(store, primaryModelClass, payload);
if (meta) {
assert(
'The `meta` returned from `extractMeta` has to be an object, not "' + typeOf(meta) + '".',
typeOf(meta) === 'object'
);
documentHash.meta = meta;
}
if (isSingle) {
let { data, included } = this.normalize(primaryModelClass, payload);
documentHash.data = data;
if (included) {
documentHash.included = included;
}
} else {
let ret = new Array(payload.length);
for (let i = 0, l = payload.length; i < l; i++) {
let item = payload[i];
let { data, included } = this.normalize(primaryModelClass, item);
if (included) {
documentHash.included = documentHash.included.concat(included);
}
ret[i] = data;
}
documentHash.data = ret;
}
return documentHash;
},
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a Model class), the property where the hash was
originally found, and the hash to normalize.
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
Example
```app/serializers/application.js
import JSONSerializer from '@ember-data/serializer/json';
import { underscore } from '@ember/string';
import { get } from '@ember/object';
export default class ApplicationSerializer extends JSONSerializer {
normalize(typeClass, hash) {
let fields = get(typeClass, 'fields');
fields.forEach(function(type, field) {
let payloadField = underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return super.normalize(...arguments);
}
}
```
@method normalize
@public
@param {Model} typeClass
@param {Object} hash
@return {Object}
*/
normalize(modelClass, resourceHash) {
let data = null;
if (resourceHash) {
this.normalizeUsingDeclaredMapping(modelClass, resourceHash);
if (typeOf(resourceHash.links) === 'object') {
this.normalizeUsingDeclaredMapping(modelClass, resourceHash.links);
}
data = {
id: this.extractId(modelClass, resourceHash),
type: modelClass.modelName,
attributes: this.extractAttributes(modelClass, resourceHash),
relationships: this.extractRelationships(modelClass, resourceHash),
};
this.applyTransforms(modelClass, data.attributes);
}
return { data };
},
/**
Returns the resource's ID.
@method extractId
@public
@param {Object} modelClass
@param {Object} resourceHash
@return {String}
*/
extractId(modelClass, resourceHash) {
let primaryKey = get(this, 'primaryKey');
let id = resourceHash[primaryKey];
return coerceId(id);
},
/**
Returns the resource's attributes formatted as a JSON-API "attributes object".
http://jsonapi.org/format/#document-resource-object-attributes
@method extractAttributes
@public
@param {Object} modelClass
@param {Object} resourceHash
@return {Object}
*/
extractAttributes(modelClass, resourceHash) {
let attributeKey;
let attributes = {};
modelClass.eachAttribute((key) => {
attributeKey = this.keyForAttribute(key, 'deserialize');
if (resourceHash[attributeKey] !== undefined) {
attributes[key] = resourceHash[attributeKey];
}
});
return attributes;
},
/**
Returns a relationship formatted as a JSON-API "relationship object".
http://jsonapi.org/format/#document-resource-object-relationships
@method extractRelationship
@public
@param {Object} relationshipModelName
@param {Object} relationshipHash
@return {Object}
*/
extractRelationship(relationshipModelName, relationshipHash) {
if (isNone(relationshipHash)) {
return null;
}
/*
When `relationshipHash` is an object it usually means that the relationship
is polymorphic. It could however also be embedded resources that the
EmbeddedRecordsMixin has be able to process.
*/
if (typeOf(relationshipHash) === 'object') {
if (relationshipHash.id) {
relationshipHash.id = coerceId(relationshipHash.id);
}
let modelClass = this.store.modelFor(relationshipModelName);
if (relationshipHash.type && !modelHasAttributeOrRelationshipNamedType(modelClass)) {
relationshipHash.type = this.modelNameFromPayloadKey(relationshipHash.type);
}
return relationshipHash;
}
return { id: coerceId(relationshipHash), type: relationshipModelName };
},
/**
Returns a polymorphic relationship formatted as a JSON-API "relationship object".
http://jsonapi.org/format/#document-resource-object-relationships
`relationshipOptions` is a hash which contains more information about the
polymorphic relationship which should be extracted:
- `resourceHash` complete hash of the resource the relationship should be
extracted from
- `relationshipKey` key under which the value for the relationship is
extracted from the resourceHash
- `relationshipMeta` meta information about the relationship
@method extractPolymorphicRelationship
@public
@param {Object} relationshipModelName
@param {Object} relationshipHash
@param {Object} relationshipOptions
@return {Object}
*/
extractPolymorphicRelationship(relationshipModelName, relationshipHash, relationshipOptions) {
return this.extractRelationship(relationshipModelName, relationshipHash);
},
/**
Returns the resource's relationships formatted as a JSON-API "relationships object".
http://jsonapi.org/format/#document-resource-object-relationships
@method extractRelationships
@public
@param {Object} modelClass
@param {Object} resourceHash
@return {Object}
*/
extractRelationships(modelClass, resourceHash) {
let relationships = {};
modelClass.eachRelationship((key, relationshipMeta) => {
let relationship = null;
let relationshipKey = this.keyForRelationship(key, relationshipMeta.kind, 'deserialize');
if (resourceHash[relationshipKey] !== undefined) {
let data = null;
let relationshipHash = resourceHash[relationshipKey];
if (relationshipMeta.kind === 'belongsTo') {
if (relationshipMeta.options.polymorphic) {
// extracting a polymorphic belongsTo may need more information
// than the type and the hash (which might only be an id) for the
// relationship, hence we pass the key, resource and
// relationshipMeta too
data = this.extractPolymorphicRelationship(relationshipMeta.type, relationshipHash, {
key,
resourceHash,
relationshipMeta,
});
} else {
data = this.extractRelationship(relationshipMeta.type, relationshipHash);
}
} else if (relationshipMeta.kind === 'hasMany') {
if (!isNone(relationshipHash)) {
data = new Array(relationshipHash.length);
if (relationshipMeta.options.polymorphic) {
for (let i = 0, l = relationshipHash.length; i < l; i++) {
let item = relationshipHash[i];
data[i] = this.extractPolymorphicRelationship(relationshipMeta.type, item, {
key,
resourceHash,
relationshipMeta,
});
}
} else {
for (let i = 0, l = relationshipHash.length; i < l; i++) {
let item = relationshipHash[i];
data[i] = this.extractRelationship(relationshipMeta.type, item);
}
}
}
}
relationship = { data };
}
let linkKey = this.keyForLink(key, relationshipMeta.kind);
if (resourceHash.links && resourceHash.links[linkKey] !== undefined) {
let related = resourceHash.links[linkKey];
relationship = relationship || {};
relationship.links = { related };
}
if (relationship) {
relationships[key] = relationship;
}
});
return relationships;
},
/**
Dasherizes the model name in the payload
@method modelNameFromPayloadKey
@public
@param {String} key
@return {String} the model's modelName
*/
modelNameFromPayloadKey(key) {
return normalizeModelName(key);
},
/**
@method normalizeRelationships
@private
*/
normalizeRelationships(typeClass, hash) {
let payloadKey;
if (this.keyForRelationship) {
typeClass.eachRelationship((key, relationship) => {
payloadKey = this.keyForRelationship(key, relationship.kind, 'deserialize');
if (key === payloadKey) {
return;
}
if (hash[payloadKey] === undefined) {
return;
}
hash[key] = hash[payloadKey];
delete hash[payloadKey];
});
}
},
/**
@method normalizeUsingDeclaredMapping
@private
*/
normalizeUsingDeclaredMapping(modelClass, hash) {
let attrs = get(this, 'attrs');
let normalizedKey;
let payloadKey;
if (attrs) {
for (let key in attrs) {
normalizedKey = payloadKey = this._getMappedKey(key, modelClass);
if (hash[payloadKey] === undefined) {
continue;
}
if (get(modelClass, 'attributes').has(key)) {
normalizedKey = this.keyForAttribute(key);
}
if (get(modelClass, 'relationshipsByName').has(key)) {
normalizedKey = this.keyForRelationship(key);
}
if (payloadKey !== normalizedKey) {
hash[normalizedKey] = hash[payloadKey];
delete hash[payloadKey];
}
}
}
},
/**
Looks up the property key that was set by the custom `attr` mapping
passed to the serializer.
@method _getMappedKey
@private
@param {String} key
@return {String} key
*/
_getMappedKey(key, modelClass) {
warn(
'There is no attribute or relationship with the name `' +
key +
'` on `' +
modelClass.modelName +
'`. Check your serializers attrs hash.',
get(modelClass, 'attributes').has(key) || get(modelClass, 'relationshipsByName').has(key),
{
id: 'ds.serializer.no-mapped-attrs-key',
}
);
let attrs = get(this, 'attrs');
let mappedKey;
if (attrs && attrs[key]) {
mappedKey = attrs[key];
//We need to account for both the { title: 'post_title' } and
//{ title: { key: 'post_title' }} forms
if (mappedKey.key) {
mappedKey = mappedKey.key;
}
if (typeof mappedKey === 'string') {
key = mappedKey;
}
}
return key;
},
/**
Check attrs.key.serialize property to inform if the `key`
can be serialized
@method _canSerialize
@private
@param {String} key
@return {boolean} true if the key can be serialized
*/
_canSerialize(key) {
let attrs = get(this, 'attrs');
return !attrs || !attrs[key] || attrs[key].serialize !== false;
},
/**
When attrs.key.serialize is set to true then
it takes priority over the other checks and the related
attribute/relationship will be serialized
@method _mustSerialize
@private
@param {String} key
@return {boolean} true if the key must be serialized
*/
_mustSerialize(key) {
let attrs = get(this, 'attrs');
return attrs && attrs[key] && attrs[key].serialize === true;
},
/**
Check if the given hasMany relationship should be serialized
By default only many-to-many and many-to-none relationships are serialized.
This could be configured per relationship by Serializer's `attrs` object.
@method shouldSerializeHasMany
@public
@param {Snapshot} snapshot
@param {String} key
@param {String} relationshipType
@return {boolean} true if the hasMany relationship should be serialized
*/
shouldSerializeHasMany(snapshot, key, relationship) {
let relationshipType = snapshot.type.determineRelationshipType(relationship, this.store);
if (this._mustSerialize(key)) {
return true;
}
return this._canSerialize(key) && (relationshipType === 'manyToNone' || relationshipType === 'manyToMany');
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```app/models/comment.js
import Model, { attr, belongsTo } from '@ember-data/model';
export default class CommentModel extends Model {
@attr title;
@attr body;
@belongsTo('user') author;
}
```
The default serialization would create a JSON object like:
```javascript
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.