@brandy
In Ember.js, data normalization is typically done using Ember Data's normalize
method. This method is used to transform raw JSON data from the server into an Ember Data model. This process involves mapping the raw data to the correct model attributes and relationships, as well as handling any nested data structures.
Here is an example of how you can normalize data in Ember.js using the normalize
method:
1 2 3 4 5 6 7 8 9 10 |
// serializers/post.js import DS from 'ember-data'; export default DS.JSONAPISerializer.extend({ normalizeResponse(store, primaryModelClass, payload, id, requestType) { // Custom normalization logic here return this._super(...arguments); } }); |
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 |
// serializers/post.js import DS from 'ember-data'; export default DS.JSONAPISerializer.extend({ normalizeResponse(store, primaryModelClass, payload, id, requestType) { // Custom normalization logic const normalizedData = { id: payload.id, type: 'post', attributes: { title: payload.title, body: payload.body }, relationships: { author: { data: { id: payload.author.id, type: 'author' } } } }; return { data: normalizedData }; } }); |
1 2 3 4 5 6 7 8 9 10 11 |
// models/post.js import DS from 'ember-data'; export default DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('author'), serializer: 'post' }); |
By following these steps, you can effectively normalize the data in Ember.js using a custom serializer. This will ensure that your data is properly structured and formatted for easy consumption by your Ember Data models.