theremin
theremin

Reputation: 120

transform json to work with ember-data

When visiting my test api it returns a json in the following format to my ember application:

{
  { "1" : {
        "id" : "1",
        "name" : "test1",
        "amount" : "12,90"
     } 
  },
  { "2" : {
        "id" : "2",
        "name" : "test2",
        "amount" : "9,30"
     } 
  },
}

My Model for the data is looks like this:

var budget = DS.Model.extend({

   amount:   DS.attr('string'),
   name:   DS.attr('string')
});
export default budget;

With the given JSON my hbs template render nothing as no model was set by ember data... The format i would expect looks like the following example:

{
  [{
        "id" : "1",
        "name" : "test1",
        "amount" : "12,90"
   },
   {
        "id" : "2",
        "name" : "test2",
        "amount" : "9,30" 
   }]
}

Is there a possibility to transform the upper json to the json i expected? I am using the Ember App Kit for my application. As API i want to use SLIM Php Framework with NotORM.

Upvotes: 1

Views: 113

Answers (1)

TheDude
TheDude

Reputation: 3952

EmberData expects the JSON format returned by your API to be in this format for all budgets:

{
  "budgets":
      [{
        "id" : "1",
        "name" : "test1",
        "amount" : "12,90"
       },
       {
        "id" : "2",
        "name" : "test2",
        "amount" : "9,30" 
       }]
}

And for a single budget, it expects:

{
  "budget": { "id": 2, "name": "test", "amount": "9,30" }
}

If you want to override this by creating your own extractSingle and extract methods in the BudgetSerializer. You can find more info here

App.BudgetSerializer = DS.RESTSerializer.extend({
  // First, restructure the top-level so it's organized by type
  extractSingle: function(store, type, payload, id, requestType) {
    // do your transformation
    return this._super(store, type, payload, id, requestType);
  }
});

Upvotes: 1

Related Questions