2

I am working with Ember and Ember-data. But the JSON which i receive is not par with the Ember side-loading standards. The JSON does'nt have a root model. Also the models are embedded and some times haves Ids and sometimes does not have Id.

I have seen couple of links on how to add root model using extract hook and also how to play with embedded model using

App.ColorSerializer = DS.RestSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    foos: {embedded: 'always'}
  }
});

This code is taken from this link.

This is the JSON used there

{
 colors:[
  {
    id: 1,
    color: "red",
    foos:[
      {
        id:1,
        name:'something 1'
      },
      {
        id:2,
        name:'something 2'
      }
    ]
  },
 ...

Now the problem that i am facing is that my JSON could also look like below(no root model "color")

{
    id: 1,
    color: "red",
    foos:[
      {
        id:1,
        name:'something 1'
      },
      {
        id:2,
        name:'something 2'
     }
  ]
},
...

or even like this(without Ids for foo objects)

{
    id: 1,
    color: "red",
    foos:[
      {
        name:'something 1'
      },
      {
        name:'something 2'
     }
  ]
},
...

Is there any way i can handle this? How do i add Ids to the embedded model foo? Also is there some solution/plugin which would accept any kind of embedded JSON and convert it into side loaded JSON and added Ids if needed.

I have seen this solution. Does it really work? Because it does not use the latest EmbeddedRecordsMixin

Community
  • 1
  • 1
aneeshere
  • 509
  • 5
  • 16

1 Answers1

3

I used a generic transform for arrays:

// /transforms/array.js
import DS from "ember-data";
import Ember from "ember";

export default DS.Transform.extend({
    deserialize: function (value) {
        if (Ember.isArray(value)) {
            return Ember.A(value);
        } else {
            return Ember.A();
        }
    },
    serialize: function (value) {
        if (Ember.isArray(value)) {
            return Ember.A(value);
        } else {
            return Ember.A();
        }
    }
});

Then in my model, I simply use:

foos: DS.attr("array")
  • That is quite a good approach and it makes sense as well. Also i would not be required to do many dirty work in the serializer unless to add the root object if that is missing. Thanks mate let me try this one – aneeshere Jul 23 '15 at 17:02