json subdocuments in ember data model

风格不统一 提交于 2019-12-12 00:58:27

问题


I have a web service that returns something like this, where there is a fixed envelope and then a body that is json with a schema that depends on "body_schema". I'd like to be able to use ember-data to manage these, with first class fields for the fixed envelope and just an object for the body field. Is this possible? I can't seem to see anything like this in the docs but I can't imagine I'm the first with this issue.

{"messages":
[
  {"id":"5",
   "from": "someone",
   "to": "somebody",
   "body_schema": "atype", 
   "body": {
     {"url":"http://localhost:3030/blobs/511d63ddd0a6b5e863000001"}
   }
  }
]}

Any ideas?


回答1:


with ember-data 1.0beta:

App.RawTransform = DS.Transform.extend({
  deserialize: function(serialized) {
    return serialized;
  },
  serialize: function(deserialized) {
    return deserialized;
  }
});

ex.

App.Foo = DS.Model.extend({
    bar: attr('raw'),
})

see https://github.com/emberjs/data/blob/master/TRANSITION.md




回答2:


I solved this - what you need to do is add your own attribute transform to the existing set of JSONTransforms. I defined an object transform like this in my app.js:

DS.JSONTransforms.object = {
    deserialize: function(serialized) {
      return Em.isNone(serialized) ? {} : serialized;
    },
    serialize: function(deserialized) {
      return Em.isNone(deserialized) ? {} : deserialized;
    }
};

With this in place, I can define a messages model like this:

App.Message = DS.Model.extend({
  timestamp: DS.attr('date'),
  body: DS.attr('object'),
  ...
});


来源:https://stackoverflow.com/questions/14972985/json-subdocuments-in-ember-data-model

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