/
serializer.js
1307 lines (1038 loc) · 41.5 KB
/
serializer.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
var get = Ember.get, set = Ember.set, map = Ember.ArrayPolyfills.map, isNone = Ember.isNone;
function mustImplement(name) {
return function() {
throw new Ember.Error("Your serializer " + this.toString() + " does not implement the required method " + name);
};
}
/**
A serializer is responsible for serializing and deserializing a group of
records.
`DS.Serializer` is an abstract base class designed to help you build a
serializer that can read to and write from any serialized form. While most
applications will use `DS.JSONSerializer`, which reads and writes JSON, the
serializer architecture allows your adapter to transmit things like XML,
strings, or custom binary data.
Typically, your application's `DS.Adapter` is responsible for both creating a
serializer as well as calling the appropriate methods when it needs to
materialize data or serialize a record.
The serializer API is designed as a series of layered hooks that you can
override to customize any of the individual steps of serialization and
deserialization.
The hooks are organized by the three responsibilities of the serializer:
1. Determining naming conventions
2. Serializing records into a serialized form
3. Deserializing records from a serialized form
Because Ember Data lazily materializes records, the deserialization
step, and therefore the hooks you implement, are split into two phases:
1. Extraction, where the serialized forms for multiple records are
extracted from a single payload. The IDs of each record are also
extracted for indexing.
2. Materialization, where a newly-created record has its attributes
and relationships initialized based on the serialized form loaded
by the adapter.
Additionally, a serializer can convert values from their JavaScript
versions into their serialized versions via a declarative API.
## Naming Conventions
One of the most common uses of the serializer is to map attribute names
from the serialized form to your `DS.Model`. For example, in your model,
you may have an attribute called `firstName`:
```javascript
App.Person = DS.Model.extend({
firstName: DS.attr('string')
});
```
However, because the web API your adapter is communicating with is
legacy, it calls this attribute `FIRST_NAME`.
You can determine the attribute name used in the serialized form
by implementing `keyForAttributeName`:
```javascript
keyForAttributeName: function(type, name) {
return name.underscore.toUpperCase();
}
```
If your attribute names are not predictable, you can re-map them
one-by-one using the adapter's `map` API:
```javascript
App.Adapter.map('App.Person', {
firstName: { key: '*API_USER_FIRST_NAME*' }
});
```
This API will also work for relationships and primary keys. For
example:
```javascript
App.Adapter.map('App.Person', {
primaryKey: '_id'
});
```
## Serialization
During the serialization process, a record or records are converted
from Ember.js objects into their serialized form.
These methods are designed in layers, like a delicious 7-layer
cake (but with fewer layers).
The main entry point for serialization is the `serialize`
method, which takes the record and options.
The `serialize` method is responsible for:
* turning the record's attributes (`DS.attr`) into
attributes on the JSON object.
* optionally adding the record's ID onto the hash
* adding relationships (`DS.hasMany` and `DS.belongsTo`)
to the JSON object.
Depending on the backend, the serializer can choose
whether to include the `hasMany` or `belongsTo`
relationships on the JSON hash.
For very custom serialization, you can implement your
own `serialize` method. In general, however, you will want
to override the hooks described below.
### Adding the ID
The default `serialize` will optionally call your serializer's
`addId` method with the JSON hash it is creating, the
record's type, and the record's ID. The `serialize` method
will not call `addId` if the record's ID is undefined.
Your adapter must specifically request ID inclusion by
passing `{ includeId: true }` as an option to `serialize`.
NOTE: You may not want to include the ID when updating an
existing record, because your server will likely disallow
changing an ID after it is created, and the PUT request
itself will include the record's identification.
By default, `addId` will:
1. Get the primary key name for the record by calling
the serializer's `primaryKey` with the record's type.
Unless you override the `primaryKey` method, this
will be `'id'`.
2. Assign the record's ID to the primary key in the
JSON hash being built.
If your backend expects a JSON object with the primary
key at the root, you can just override the `primaryKey`
method on your serializer subclass.
Otherwise, you can override the `addId` method for
more specialized handling.
### Adding Attributes
By default, the serializer's `serialize` method will call
`addAttributes` with the JSON object it is creating
and the record to serialize.
The `addAttributes` method will then call `addAttribute`
in turn, with the JSON object, the record to serialize,
the attribute's name and its type.
Finally, the `addAttribute` method will serialize the
attribute:
1. It will call `keyForAttributeName` to determine
the key to use in the JSON hash.
2. It will get the value from the record.
3. It will call `serializeValue` with the attribute's
value and attribute type to convert it into a
JSON-compatible value. For example, it will convert a
Date into a String.
If your backend expects a JSON object with attributes as
keys at the root, you can just override the `serializeValue`
and `keyForAttributeName` methods in your serializer
subclass and let the base class do the heavy lifting.
If you need something more specialized, you can probably
override `addAttribute` and let the default `addAttributes`
handle the nitty gritty.
### Adding Relationships
By default, `serialize` will call your serializer's
`addRelationships` method with the JSON object that is
being built and the record being serialized. The default
implementation of this method is to loop over all of the
relationships defined on your record type and:
* If the relationship is a `DS.hasMany` relationship,
call `addHasMany` with the JSON object, the record
and a description of the relationship.
* If the relationship is a `DS.belongsTo` relationship,
call `addBelongsTo` with the JSON object, the record
and a description of the relationship.
The relationship description has the following keys:
* `type`: the class of the associated information (the
first parameter to `DS.hasMany` or `DS.belongsTo`)
* `kind`: either `hasMany` or `belongsTo`
The relationship description may get additional
information in the future if more capabilities or
relationship types are added. However, it will
remain backwards-compatible, so the mere existence
of new features should not break existing adapters.
@module data
@submodule data-serializer
@main data-serializer
@class Serializer
@namespace DS
@extends Ember.Object
@constructor
*/
DS.Serializer = Ember.Object.extend({
init: function() {
this.mappings = Ember.Map.create();
this.aliases = Ember.Map.create();
this.configurations = Ember.Map.create();
this.globalConfigurations = {};
},
extract: mustImplement('extract'),
extractMany: mustImplement('extractMany'),
extractId: mustImplement('extractId'),
extractAttribute: mustImplement('extractAttribute'),
extractHasMany: mustImplement('extractHasMany'),
extractBelongsTo: mustImplement('extractBelongsTo'),
extractRecordRepresentation: function(loader, type, data, shouldSideload) {
var prematerialized = {}, reference;
if (shouldSideload) {
reference = loader.sideload(type, data);
} else {
reference = loader.load(type, data);
}
this.eachEmbeddedHasMany(type, function(name, relationship) {
var embeddedData = this.extractEmbeddedData(data, this.keyFor(relationship));
if (!isNone(embeddedData)) {
this.extractEmbeddedHasMany(loader, relationship, embeddedData, reference, prematerialized);
}
}, this);
this.eachEmbeddedBelongsTo(type, function(name, relationship) {
var embeddedData = this.extractEmbeddedData(data, this.keyFor(relationship));
if (!isNone(embeddedData)) {
this.extractEmbeddedBelongsTo(loader, relationship, embeddedData, reference, prematerialized);
}
}, this);
loader.prematerialize(reference, prematerialized);
return reference;
},
extractEmbeddedHasMany: function(loader, relationship, array, parent, prematerialized) {
var references = map.call(array, function(item) {
if (!item) { return; }
var foundType = this.extractEmbeddedType(relationship, item),
reference = this.extractRecordRepresentation(loader, foundType, item, true);
// If the embedded record should also be saved back when serializing the parent,
// make sure we set its parent since it will not have an ID.
var embeddedType = this.embeddedType(parent.type, relationship.key);
if (embeddedType === 'always') {
reference.parent = parent;
}
// If the embedded children have an inverse belongs-to, set the
// inverse to the current record in their prematerialized data.
var parentType = relationship.parentType,
inverse = parentType.inverseFor(relationship.key);
if (inverse) {
var inverseName = inverse.name;
reference.prematerialized[inverseName] = parent;
}
return reference;
}, this);
prematerialized[relationship.key] = references;
},
extractEmbeddedBelongsTo: function(loader, relationship, data, parent, prematerialized) {
var foundType = this.extractEmbeddedType(relationship, data),
reference = this.extractRecordRepresentation(loader, foundType, data, true);
prematerialized[relationship.key] = reference;
// If the embedded record should also be saved back when serializing the parent,
// make sure we set its parent since it will not have an ID.
var embeddedType = this.embeddedType(parent.type, relationship.key);
if (embeddedType === 'always') {
reference.parent = parent;
}
},
/**
A hook you can use to customize how the record's type is extracted from
the serialized data.
The `extractEmbeddedType` hook is called with:
* the relationship
* the serialized representation of the record
By default, it returns the type of the relationship.
@method extractEmbeddedType
@param {Object} relationship an object representing the relationship
@param {any} data the serialized representation of the record
*/
extractEmbeddedType: function(relationship, data) {
return relationship.type;
},
/**
A hook you need to implement in order to extract
the data associated with an embedded record.
@param {any} data the serialized representation of the record
@param {String} key the key that represents the embedded record
*/
extractEmbeddedData: mustImplement(),
//.......................
//. SERIALIZATION HOOKS
//.......................
/**
The main entry point for serializing a record. While you can consider this
a hook that can be overridden in your serializer, you will have to manually
handle serialization. For most cases, there are more granular hooks that you
can override.
If overriding this method, these are the responsibilities that you will need
to implement yourself:
* If the option hash contains `includeId`, add the record's ID to the serialized form.
By default, `serialize` calls `addId` if appropriate.
* If the option hash contains `includeType`, add the record's type to the serialized form.
* Add the record's attributes to the serialized form. By default, `serialize` calls
`addAttributes`.
* Add the record's relationships to the serialized form. By default, `serialize` calls
`addRelationships`.
@method serialize
@param {DS.Model} record the record to serialize
@param {Object} [options] a hash of options
@returns {any} the serialized form of the record
*/
serialize: function(record, options) {
options = options || {};
var serialized = this.createSerializedForm(), id;
if (options.includeId) {
if (id = get(record, 'id')) {
this._addId(serialized, record.constructor, id);
}
}
if (options.includeType) {
this.addType(serialized, record.constructor);
}
this.addAttributes(serialized, record);
this.addRelationships(serialized, record);
return serialized;
},
/**
@private
Given an attribute type and value, convert the value into the
serialized form using the transform registered for that type.
@method serializeValue
@param {any} value the value to convert to the serialized form
@param {String} attributeType the registered type (e.g. `string`
or `boolean`)
@returns {any} the serialized form of the value
*/
serializeValue: function(value, attributeType) {
var transform = this.transforms ? this.transforms[attributeType] : null;
Ember.assert("You tried to use an attribute type (" + attributeType + ") that has not been registered", transform);
return transform.serialize(value);
},
/**
A hook you can use to normalize IDs before adding them to the
serialized representation.
Because the store coerces all IDs to strings for consistency,
this is the opportunity for the serializer to, for example,
convert numerical IDs back into number form.
Null or undefined ids will resolve to a null value.
@param {String} id the id from the record
@returns {any} the serialized representation of the id
*/
serializeId: function(id) {
if(Ember.isEmpty(id)) { return null; }
if(isNaN(+id)) { return id; }
return +id;
},
/**
A hook you can use to change how attributes are added to the serialized
representation of a record.
By default, `addAttributes` simply loops over all of the attributes of the
passed record, maps the attribute name to the key for the serialized form,
and invokes any registered transforms on the value. It then invokes the
more granular `addAttribute` with the key and transformed value.
Since you can override `keyForAttributeName`, `addAttribute`, and register
custom transforms, you should rarely need to override this hook.
@method addAttributes
@param {any} data the serialized representation that is being built
@param {DS.Model} record the record to serialize
*/
addAttributes: function(data, record) {
record.eachAttribute(function(name, attribute) {
this._addAttribute(data, record, name, attribute.type);
}, this);
},
/**
A hook you can use to customize how the key/value pair is added to
the serialized data.
@method addAttribute
@param {any} serialized the serialized form being built
@param {String} key the key to add to the serialized data
@param {any} value the value to add to the serialized data
*/
addAttribute: mustImplement('addAttribute'),
/**
A hook you can use to customize how the record's id is added to
the serialized data.
The `addId` hook is called with:
* the serialized representation being built
* the resolved primary key (taking configurations and the
`primaryKey` hook into consideration)
* the serialized id (after calling the `serializeId` hook)
@method addId
@param {any} data the serialized representation that is being built
@param {String} key the resolved primary key
@param {id} id the serialized id
*/
addId: mustImplement('addId'),
/**
A hook you can use to customize how the record's type is added to
the serialized data.
The `addType` hook is called with:
* the serialized representation being built
* the serialized id (after calling the `serializeId` hook)
@method addType
@param {any} data the serialized representation that is being built
@param {DS.Model subclass} type the type of the record
*/
addType: Ember.K,
/**
Creates an empty hash that will be filled in by the hooks called from the
`serialize()` method.
@method createSerializedForm
@return {Object}
*/
createSerializedForm: function() {
return {};
},
/**
A hook you can use to change how relationships are added to the serialized
representation of a record.
By default, `addRelationships` loops over all of the relationships of the
passed record, maps the relationship names to the key for the serialized form,
and then invokes the public `addBelongsTo` and `addHasMany` hooks.
Since you can override `keyForBelongsTo`, `keyForHasMany`, `addBelongsTo`,
`addHasMany`, and register mappings, you should rarely need to override this
hook.
@method addRelationships
@param {any} data the serialized representation that is being built
@param {DS.Model} record the record to serialize
*/
addRelationships: function(data, record) {
record.eachRelationship(function(name, relationship) {
if (relationship.kind === 'belongsTo') {
this._addBelongsTo(data, record, name, relationship);
} else if (relationship.kind === 'hasMany') {
this._addHasMany(data, record, name, relationship);
}
}, this);
},
/**
A hook you can use to add a `belongsTo` relationship to the
serialized representation.
The specifics of this hook are very adapter-specific, so there
is no default implementation. You can see `DS.JSONSerializer`
for an example of an implementation of the `addBelongsTo` hook.
The `belongsTo` relationship object has the following properties:
* **type** a subclass of DS.Model that is the type of the
relationship. This is the first parameter to DS.belongsTo
* **options** the options passed to the call to DS.belongsTo
* **kind** always `belongsTo`
Additional properties may be added in the future.
@method addBelongsTo
@param {any} data the serialized representation that is being built
@param {DS.Model} record the record to serialize
@param {String} key the key for the serialized object
@param {Object} relationship an object representing the relationship
*/
addBelongsTo: mustImplement('addBelongsTo'),
/**
A hook you can use to add a `hasMany` relationship to the
serialized representation.
The specifics of this hook are very adapter-specific, so there
is no default implementation. You may not need to implement this,
for example, if your backend only expects relationships on the
child of a one to many relationship.
The `hasMany` relationship object has the following properties:
* **type** a subclass of DS.Model that is the type of the
relationship. This is the first parameter to DS.hasMany
* **options** the options passed to the call to DS.hasMany
* **kind** always `hasMany`
Additional properties may be added in the future.
@method addHasMany
@param {any} data the serialized representation that is being built
@param {DS.Model} record the record to serialize
@param {String} key the key for the serialized object
@param {Object} relationship an object representing the relationship
*/
addHasMany: mustImplement('addHasMany'),
/**
NAMING CONVENTIONS
The most commonly overridden APIs of the serializer are
the naming convention methods:
* `keyForAttributeName`: converts a camelized attribute name
into a key in the adapter-provided data hash. For example,
if the model's attribute name was `firstName`, and the
server used underscored names, you would return `first_name`.
* `primaryKey`: returns the key that should be used to
extract the id from the adapter-provided data hash. It is
also used when serializing a record.
*/
/**
A hook you can use in your serializer subclass to customize
how an unmapped attribute name is converted into a key.
By default, this method returns the `name` parameter.
For example, if the attribute names in your JSON are underscored,
you will want to convert them into JavaScript conventional
camelcase:
```javascript
App.MySerializer = DS.Serializer.extend({
// ...
keyForAttributeName: function(type, name) {
return name.camelize();
}
});
```
@method keyForAttributeName
@param {DS.Model subclass} type the type of the record with
the attribute name `name`
@param {String} name the attribute name to convert into a key
@returns {String} the key
*/
keyForAttributeName: function(type, name) {
return name;
},
/**
A hook you can use in your serializer to specify a conventional
primary key.
By default, this method will return the string `id`.
In general, you should not override this hook to specify a special
primary key for an individual type; use `configure` instead.
For example, if your primary key is always `__id__`:
```javascript
App.MySerializer = DS.Serializer.extend({
// ...
primaryKey: function(type) {
return '__id__';
}
});
```
In another example, if the primary key always includes the
underscored version of the type before the string `id`:
```javascript
App.MySerializer = DS.Serializer.extend({
// ...
primaryKey: function(type) {
// If the type is `BlogPost`, this will return
// `blog_post_id`.
var typeString = type.toString().split(".")[1].underscore();
return typeString + "_id";
}
});
```
@method primaryKey
@param {DS.Model subclass} type
@returns {String} the primary key for the type
*/
primaryKey: function(type) {
return "id";
},
/**
A hook you can use in your serializer subclass to customize
how an unmapped `belongsTo` relationship is converted into
a key.
By default, this method calls `keyForAttributeName`, so if
your naming convention is uniform across attributes and
relationships, you can use the default here and override
just `keyForAttributeName` as needed.
For example, if the `belongsTo` names in your JSON always
begin with `BT_` (e.g. `BT_posts`), you can strip out the
`BT_` prefix:"
```javascript
App.MySerializer = DS.Serializer.extend({
// ...
keyForBelongsTo: function(type, name) {
return name.match(/^BT_(.*)$/)[1].camelize();
}
});
```
@method keyForBelongsTo
@param {DS.Model subclass} type the type of the record with
the `belongsTo` relationship.
@param {String} name the relationship name to convert into a key
@returns {String} the key
*/
keyForBelongsTo: function(type, name) {
return this.keyForAttributeName(type, name);
},
/**
A hook you can use in your serializer subclass to customize
how an unmapped `hasMany` relationship is converted into
a key.
By default, this method calls `keyForAttributeName`, so if
your naming convention is uniform across attributes and
relationships, you can use the default here and override
just `keyForAttributeName` as needed.
For example, if the `hasMany` names in your JSON always
begin with the "table name" for the current type (e.g.
`post_comments`), you can strip out the prefix:"
```javascript
App.MySerializer = DS.Serializer.extend({
// ...
keyForHasMany: function(type, name) {
// if your App.BlogPost has many App.BlogComment, the key from
// the server would look like: `blog_post_blog_comments`
//
// 1. Convert the type into a string and underscore the
// second part (App.BlogPost -> blog_post)
// 2. Extract the part after `blog_post_` (`blog_comments`)
// 3. Underscore it, to become `blogComments`
var typeString = type.toString().split(".")[1].underscore();
return name.match(new RegExp("^" + typeString + "_(.*)$"))[1].camelize();
}
});
```
@method keyForHasMany
@param {DS.Model subclass} type the type of the record with
the `belongsTo` relationship.
@param {String} name the relationship name to convert into a key
@returns {String} the key
*/
keyForHasMany: function(type, name) {
return this.keyForAttributeName(type, name);
},
//.........................
//. MATERIALIZATION HOOKS
//.........................
materialize: function(record, serialized, prematerialized) {
var id;
if (Ember.isNone(get(record, 'id'))) {
if (prematerialized && prematerialized.hasOwnProperty('id')) {
id = prematerialized.id;
} else {
id = this.extractId(record.constructor, serialized);
}
record.materializeId(id);
}
this.materializeAttributes(record, serialized, prematerialized);
this.materializeRelationships(record, serialized, prematerialized);
},
deserializeValue: function(value, attributeType) {
var transform = this.transforms ? this.transforms[attributeType] : null;
Ember.assert("You tried to use an attribute type (" + attributeType + ") that has not been registered", transform);
return transform.deserialize(value);
},
materializeAttributes: function(record, serialized, prematerialized) {
record.eachAttribute(function(name, attribute) {
if (prematerialized && prematerialized.hasOwnProperty(name)) {
record.materializeAttribute(name, prematerialized[name]);
} else {
this.materializeAttribute(record, serialized, name, attribute.type);
}
}, this);
},
materializeAttribute: function(record, serialized, attributeName, attributeType) {
var value = this.extractAttribute(record.constructor, serialized, attributeName);
value = this.deserializeValue(value, attributeType);
record.materializeAttribute(attributeName, value);
},
materializeRelationships: function(record, serialized, prematerialized) {
record.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
if (prematerialized && prematerialized.hasOwnProperty(name)) {
var tuplesOrReferencesOrOpaque = this._convertPrematerializedHasMany(relationship.type, prematerialized[name]);
record.materializeHasMany(name, tuplesOrReferencesOrOpaque);
} else {
this.materializeHasMany(name, record, serialized, relationship, prematerialized);
}
} else if (relationship.kind === 'belongsTo') {
if (prematerialized && prematerialized.hasOwnProperty(name)) {
var tupleOrReference = this._convertTuple(relationship.type, prematerialized[name]);
record.materializeBelongsTo(name, tupleOrReference);
} else {
this.materializeBelongsTo(name, record, serialized, relationship, prematerialized);
}
}
}, this);
},
materializeHasMany: function(name, record, hash, relationship) {
var type = record.constructor,
key = this._keyForHasMany(type, relationship.key),
idsOrTuples = this.extractHasMany(type, hash, key),
tuples = idsOrTuples;
if(idsOrTuples && Ember.isArray(idsOrTuples)) {
tuples = this._convertTuples(relationship.type, idsOrTuples);
}
record.materializeHasMany(name, tuples);
},
materializeBelongsTo: function(name, record, hash, relationship) {
var type = record.constructor,
key = this._keyForBelongsTo(type, relationship.key),
idOrTuple,
tuple = null;
if(relationship.options && relationship.options.polymorphic) {
idOrTuple = this.extractBelongsToPolymorphic(type, hash, key);
} else {
idOrTuple = this.extractBelongsTo(type, hash, key);
}
if(!isNone(idOrTuple)) {
tuple = this._convertTuple(relationship.type, idOrTuple);
}
record.materializeBelongsTo(name, tuple);
},
_convertPrematerializedHasMany: function(type, prematerializedHasMany) {
var tuplesOrReferencesOrOpaque;
if( typeof prematerializedHasMany === 'string' ) {
tuplesOrReferencesOrOpaque = prematerializedHasMany;
} else {
tuplesOrReferencesOrOpaque = this._convertTuples(type, prematerializedHasMany);
}
return tuplesOrReferencesOrOpaque;
},
_convertTuples: function(type, idsOrTuples) {
return map.call(idsOrTuples, function(idOrTuple) {
return this._convertTuple(type, idOrTuple);
}, this);
},
_convertTuple: function(type, idOrTuple) {
var foundType;
if (typeof idOrTuple === 'object') {
if (DS.Model.detect(idOrTuple.type)) {
return idOrTuple;
} else {
foundType = this.typeFromAlias(idOrTuple.type);
Ember.assert("Unable to resolve type " + idOrTuple.type + ". You may need to configure your serializer aliases.", !!foundType);
return {id: idOrTuple.id, type: foundType};
}
}
return {id: idOrTuple, type: type};
},
/**
@private
This method is called to get the primary key for a given
type.
If a primary key configuration exists for this type, this
method will return the configured value. Otherwise, it will
call the public `primaryKey` hook.
@method _primaryKey
@param {DS.Model subclass} type
@returns {String} the primary key for the type
*/
_primaryKey: function(type) {
var config = this.configurationForType(type),
primaryKey = config && config.primaryKey;
if (primaryKey) {
return primaryKey;
} else {
return this.primaryKey(type);
}
},
/**
@private
This method looks up the key for the attribute name and transforms the
attribute's value using registered transforms.
Specifically:
1. Look up the key for the attribute name. If available, this will use
any registered mappings. Otherwise, it will invoke the public
`keyForAttributeName` hook.
2. Get the value from the record using the `attributeName`.
3. Transform the value using registered transforms for the `attributeType`.
4. Invoke the public `addAttribute` hook with the hash, key, and
transformed value.
@method _addAttribute
@param {any} data the serialized representation being built
@param {DS.Model} record the record to serialize
@param {String} attributeName the name of the attribute on the record
@param {String} attributeType the type of the attribute (e.g. `string`
or `boolean`)
*/
_addAttribute: function(data, record, attributeName, attributeType) {
var key = this._keyForAttributeName(record.constructor, attributeName);
var value = get(record, attributeName);
this.addAttribute(data, key, this.serializeValue(value, attributeType));
},
/**
@private
This method looks up the primary key for the `type` and invokes
`serializeId` on the `id`.
It then invokes the public `addId` hook with the primary key and
the serialized id.
@method _addId
@param {any} data the serialized representation that is being built
@param {Ember.Model subclass} type
@param {any} id the materialized id from the record
*/
_addId: function(hash, type, id) {
var primaryKey = this._primaryKey(type);
this.addId(hash, primaryKey, this.serializeId(id));
},
/**
@private
This method is called to get a key used in the data from
an attribute name. It first checks for any mappings before
calling the public hook `keyForAttributeName`.
@method _keyForAttributeName
@param {DS.Model subclass} type the type of the record with
the attribute name `name`
@param {String} name the attribute name to convert into a key
@returns {String} the key
*/
_keyForAttributeName: function(type, name) {
return this._keyFromMappingOrHook('keyForAttributeName', type, name);
},
/**
@private
This method is called to get a key used in the data from
a belongsTo relationship. It first checks for any mappings before
calling the public hook `keyForBelongsTo`.
@method _keyForBelongsTo
@param {DS.Model subclass} type the type of the record with
the `belongsTo` relationship.
@param {String} name the relationship name to convert into a key
@returns {String} the key
*/
_keyForBelongsTo: function(type, name) {
return this._keyFromMappingOrHook('keyForBelongsTo', type, name);
},
keyFor: function(description) {
var type = description.parentType,
name = description.key;
switch (description.kind) {
case 'belongsTo':
return this._keyForBelongsTo(type, name);
case 'hasMany':
return this._keyForHasMany(type, name);
}
},
/**
@private
This method is called to get a key used in the data from
a hasMany relationship. It first checks for any mappings before
calling the public hook `keyForHasMany`.
@method _keyForHasMany
@param {DS.Model subclass} type the type of the record with
the `hasMany` relationship.
@param {String} name the relationship name to convert into a key
@returns {String} the key
*/
_keyForHasMany: function(type, name) {
return this._keyFromMappingOrHook('keyForHasMany', type, name);
},
/**
@private