Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember Data and mapping JSON objects

I have truly searched and I have not found a decent example of using the serializer to get objects from a differently formatted JSON response. My reason for not changing the format of the JSON response is outlined here http://flask.pocoo.org/docs/security/#json-security.

I'm not very good with javascript yet so I had a hard time understanding the hooks in the serialize_json.js or maybe I should be using mapping (I just don't know). So here is an example of my JSON response for many objects:

{
  "total_pages": 1, 
  "objects": [
     {
      "is_completed": true, 
      "id": 1, 
      "title": "I need to eat"
    }, 
    {
      "is_completed": false, 
      "id": 2, 
      "title": "Hey does this work"
    }, 
    {
      "is_completed": false, 
      "id": 3, 
      "title": "Go to sleep"
    }, 
  ], 
  "num_results": 3, 
  "page": 1
}

When ember-data tries to use this I get the following error:

DEBUG: -------------------------------
DEBUG: Ember.VERSION : 1.0.0-rc.1
DEBUG: Handlebars.VERSION : 1.0.0-rc.3
DEBUG: jQuery.VERSION : 1.9.1
DEBUG: -------------------------------
Uncaught Error: assertion failed: Your server returned a hash with the key total_pages but you have no mapping for it 

Which totally makes when you look at my code for the data store:

Todos.Store = DS.Store.extend({
    revision: 12,
    adapter: DS.RESTAdapter.create({
        mappings: {objects: "Todos.Todo"},
        namespace: 'api'
    })
});

My question is how do I deal with total_pages, num_results and page? And by deal, I mean ignore so I can just map the objects array.

like image 448
Drew Larson Avatar asked Mar 11 '13 21:03

Drew Larson


2 Answers

All root properties you return in your JSON result are mapped to a DS.Model in Ember Data. You should not return properties that are not modelled or you should model them.

If you want to get rid of the error you should make an empty model for the properties you don't use.

Read more here

Why are you returning properties you don't want to use? Or is it out of your control?

like image 150
Willem de Wit Avatar answered Sep 20 '22 03:09

Willem de Wit


The way to accomplish this is with a custom serializer. If all your data is returned from the server in this format you could simply create ApplicationSerializer like this:

DS.RESTSerilizer.extend({
  normalizePayload: function(type, payload) {
     delete payload.total_pages;
     delete payload.num_results;
     delete payload.page;
     return payload;
  }
});

That should allow Ember Data to consume your API seamlessly.

like image 26
Baruch Avatar answered Sep 20 '22 03:09

Baruch