mercredi 16 mars 2016

Converting backend json response to Ember store expected format

I am pretty new to ember and trying to do some POC's to fit our existing applications.

Using ember 1.13.12 and ember data 1.13.15

I have two models,

company.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    employee: DS.hasMany('employee',{async:true}),
});

employee.js

import DS from 'ember-data';

export default DS.Model.extend({

    name: DS.attr('string'),
    alias: DS.attr('string')
});

The serializers extend the JSONSerializer and sets the primarykey for both models and the option embedded always for employee model.

Backend json response for /employee/7, - this results in error - Ember.A(...) map not a function

{
    "name": "abc"
    "employee": {
        "employeeId": 7,
        "name": "employee7",
        "alias": "e7"
    }
}

Backend json response for /employees - this gets pushed to the ember store without issues

{
    "name": "abc"
    "employee": [
        {
            "employeeId": 1,
            "name": "employee1",
            "alias": "e1"
        },
        {
            "employeeId": 7,
            "name": "employee7",
            "alias": "e7"
        }
    ]
}

With the above response I faced two issues,

  • Not having an 'id' for the 'company' model to push to the store (Workaround ended up changing the backend response to have an 'id')
  • When I try getting a single employee say employee/7/ the json response from backend does not return as an array (Workaround added one of the normalize hook and added a line payload.employee = [payload.employee] and it worked)

Is there a way I can get past the above issues without changing the backend response and workarounds.




Aucun commentaire:

Enregistrer un commentaire