Ember data 1.0 beta extractArray Serializer

What is the best way to serialize these objects? I have an array of posts, these objects include embedded objects of user.

 {
"posts": [
  {
   "id": "5226f2670364e70ae7d77266",
   "subject": "Text",
   "created": 1325410935048,
   "reporter": {
           "id": "5226f2660364e70ae7d771e2",
           "firstName": "Doris",
           "lastName": "Baumertr"
   },
  {
   "id": "5226f2670364e75644156464",
   "subject": "Post 2",
   "created": 1325410935048,
   "reporter": {
           "id": "5226f2660364e70ae7d771e2",
           "firstName": "Doris",
           "lastName": "Baumertr"
   }
 ]

}

I defined the serializer of the post object, what I should do to map embedded objects?

App.PostSerializer = DS.RESTSerializer.extend({
    extractArray: function(store, type, payload, id, requestType) {


        return this._super(store, type, payload, id, requestType);
    }
});

I think I solved the problem with the following code.

App.PostSerializer = DS.RESTSerializer.extend({
    extractArray: function(store, type, payload, id, requestType) {
        var posts =payload.posts;
        var reporters = [];
        posts.forEach(function(post){
               var reporter = post.reporter,
                   reporterId = reporter.id;
                reporters.push(reporter);
                post.reporter = reporterId;
        });
        payload.users = reporters;

        return this._super(store, type, payload, id, requestType);
    }
});

After extracting the json structure looks so:

{
"posts": [
  {
   "id": "5226f2670364e70ae7d77266",
   "subject": "Text",
   "created": 1325410935048,
   "reporter": "5226f2660364e70ae7d771e2"
   },
  {
   "id": "5226f2670364e75644156464",
   "subject": "Post 2",
   "created": 1325410935048,
   "reporter": "5226f2660364e70ae7d771e2"
 }
 ],
 "users": [
    "reporter": {
           "id": "5226f2660364e70ae7d771e2",
           "firstName": "Doris",
           "lastName": "Baumertr"
   },
    "reporter": {
           "id": "5226f2660364e70ae7d771e2",
           "firstName": "Doris",
           "lastName": "Baumertr"
   }
  ]
}
2 Likes

This doesn’t seem to work for me because the embedded resources are not saved to the store. So when you try to access the embedded object, an exception is thrown that the object does not exist in the store. I’m assuming this is because extractArray does not expect an arbitrary property to be set on the returned array (and it pukes if you return anything besides an array).

Is there an updated way to accomplish this? Are you supposed to tell it to insert those objects into the store explicitly?

Here is a GIST with the original extract* method I wrote:

https://gist.github.com/samuraisam/8140992

And this one which actually works, but I’m unsure if it’s safe to be inserting into the store here, and not sure if it takes advantage of any of those other (potentially necessary) transformations).

https://gist.github.com/samuraisam/8141094