Serialize JSON into Ember-Data (two different models in payload)

蹲街弑〆低调 提交于 2019-12-25 02:08:21

问题


I have JSON coming from the server which looks like:

data: {
       user: {
              address: {
                         id: "id",
                         city: "city",
                         street: "street",
                         .......
              }
              name: "name",
              ......
       }

       authentication: {
                         token: "token",
                         id: "id"
       }
}

In Ember I have a model auth which should represent the authentication model that I get from the server. Since I have different names for same model on the server and in the Ember store, I wrote a serializer with one method typeForRoot(root) where I just map server authentication to Ember auth. Problem is that this typeForRoot is actually never invoked, and I do not have a slightly idea why.

Here is Ember auth model:

import DS from 'ember-data';

export default DS.Model.extend({
    token: DS.attr('string')

});

And here is my serializer:

import DS from 'ember-data';
import Ember from 'ember';

export default DS.RESTSerializer.extend({

  typeForRoot: function(root) {
    // 'authentication' should become 'auth'
    var subRoot = root.substring(0, root.length - 10);

    // _super normalizes 'authentication' to 'auth'
    return this._super(subRoot);
  }
});

My user model is being properly saved in the store (I'm using a separate, model based, serializer for user), but I get the message WARNING: Encountered "authentication" in payload, but no model was found for model name "authentication" (resolved model name using shop-app@serializer:user:.typeForRoot("authentication")) when authentication model needs to be saved in auth model in the store.

Does anyone know how can I overcome this problem. Thanks, Milan


回答1:


I assume the typeForRoot you've implemented is on the auth serialiser? If you notice the error, it states:

shop-app@serializer:user:.typeForRoot("authentication")

This particularly points to the User serialiser.

I assume you're doing a request for the User model which returns the User model and Auth model in the data - since your using the User adapter and Serialiser to do this, you would need to implement the typeForRoot logic on the User serialiser.



来源:https://stackoverflow.com/questions/29604167/serialize-json-into-ember-data-two-different-models-in-payload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!