How to normalize data in ember.js?

Member

by brandy , in category: Javascript , 2 months ago

How to normalize data in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 2 months ago

@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. Define a custom serializer for your data model. This serializer will be responsible for normalizing the raw JSON data into the correct format for your Ember Data model. You can define a serializer by extending DS.JSONAPISerializer or DS.RESTSerializer depending on your API's structure.
 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. Implement the custom normalization logic inside the serializer's normalizeResponse method. This method takes the raw JSON data as input and should return a normalized JSON object that can be used to create an Ember Data model.
 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. Assign the custom serializer to your Ember Data model by setting the serializer property in the model definition.
 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.