Ember AppKit and embedded object using ember data

31 views Asked by At

I'm trying to create a model having embedded data using Ember AppKit and the ES6 syntax but I'm a bit confused.

I found this article explaining the way to embedded data into a model: https://github.com/emberjs/data/blob/master/TRANSITION.md#rest-adapter-and-serializer-configuration

But I don't know how to apply this to my scope. I should add the "map" into the adapter to specify that my attribute will be embedded, but I don't know how.

This is what I have:

adapters/item.js

export default DS.RESTAdapter.extend({
   namespace: 'path/to/api/json'
});

How to add the map here??

models/item.js

var attr = DS.attr,
    belongsTo = DS.belongsTo;

export default DS.Model.extend({
    name: attr('string')
    width: belongsTo('valueUnit'),
    height: belongsTo('valueUnit'),
    weight: belongsTo('valueUnit')
});

I think here it should look something like this:

export default DS.Model.extend({
    name: attr('string')
    width: belongsTo('valueUnit', {embedded: 'always'}),
    height: belongsTo('valueUnit', {embedded: 'always'}),
    weight: belongsTo('valueUnit', {embedded: 'always'})
});

models/value-unit.js

var attr = DS.attr;

export default DS.Model.extend({
    value: attr('number')
    unit: attr('string')
});

And this is what I get from the server:

{
  "items": [
    {
      "id": "123456789",
      "width": {
        "value": 150,
        "unit": "m"
      },
      "height": {
        "value": 5.3,
        "unit": "ft"
      },
      "weight": {
        "value": 12,
        "unit": "lb"
      }
    }
  ]
}

Thanks

1

There are 1 answers

0
ViRa On

You will have to write a serializer for item model. Here is the guide on how to write the serializer.

(In your case, you are extracting the data from items array. So implement the extractArray function.)

Hope it helps!