DS.RESTSerializer#normalize()

normalize (modelClass, resourceHash, prop) Object

Inherited from DS.JSONSerializer but overwritten in addon/serializers/rest.js:91

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 DS.Model class), the property where the hash was originally found, and the hash to normalize.

For example, if you have a payload that looks like this:

{
  "post": {
    "id": 1,
    "title": "Rails is omakase",
    "comments": [ 1, 2 ]
  },
  "comments": [{
    "id": 1,
    "body": "FIRST"
  }, {
    "id": 2,
    "body": "Rails is unagi"
  }]
}

The normalize method will be called three times:

  • With App.Post, "posts" and { id: 1, title: "Rails is omakase", ... }
  • With App.Comment, "comments" and { id: 1, body: "FIRST" }
  • With App.Comment, "comments" and { id: 2, body: "Rails is unagi" }

You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. You will only need to implement normalize and manipulate the payload as desired.

For example, if the IDs under "comments" are provided as _id instead of id, you can specify how to normalize just the comments:

app/serializers/post.js
import DS from 'ember-data';

export default DS.RESTSerializer.extend({
  normalize(model, hash, prop) {
    if (prop === 'comments') {
      hash.id = hash._id;
      delete hash._id;
    }

    return this._super(...arguments);
  }
});

On each call to the normalize method, the third parameter (prop) is always one of the keys that were in the original payload or in the result of another normalization as normalizeResponse.

Parameters:

modelClass DS.Model
resourceHash Object
prop String

Returns:

Object
doc_EmberJs
2016-11-30 16:50:36
Comments
Leave a Comment

Please login to continue.