jeudi 16 août 2018

Ember-data: How to deal with inheritance objects

I have a JSON-Api backend and I can't find the good way to deal with inheritance objects, because the Route ressource name is the parent Class but the "type" attribute in the payload correspond to the child class. Example of payload (GET /api/pets):

{
    "data": [
        {
            "id": "1",
            "type": "cat",
            "attributes": {
                "name": "Tom"
            }
        },
        {
            "id": "2",
            "type": "dog",
            "attributes": {
                "name": "Max"
        }
    ]
}

Now, I load it with a Route:

# app/routes/pets.js
import Route from '@ember/routing/route';

export default Route.extend({
  model() {
    return this.get('store').findAll('pet');
  }
});

Models:

# app/models/pet.js
import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string')
});

# app/models/cat.js
import DS from 'ember-data';
import Pet from './pet';

export default Pet.extend({
});

# app/models/dog.js
import DS from 'ember-data';
import Pet from './pet';

export default Pet.extend({
});

And finally, I want to display them on a simple page:

# app/templates/devices.hbs
<h3>Pets list</h3>


  <h4></h4>


The objects are well loaded by the Route (I saw them with the Ember inspector), but there are not Pet objects, so they are not rendered. At this point, I don't know how to deal with that, without changing the api structure.




Aucun commentaire:

Enregistrer un commentaire