Retrieving rendered json from ember .save() method

251 views Asked by At

My rails backend renders a json response when I call .save() on my model. When doing a jquery ajax PUT request like this, I can retrieve the data returned (see below, data parameter) :

$.ajax({
    type : 'PUT',
    url: '/conversations/' + conversation.id + '/assignation',
    dataType: 'json',
    data: newAssignation,
    success: function(data) {
        conversation.get('content').pushObject(data)};       
});

How can I retrieve rendered json when calling .save() method on my model?

self.store.find('conversation', conv.id).then(function(conversation){

    conversation.set('status', 'opened');
    conversation.save(); ** This returns json response that I want to retrieve **           

});
1

There are 1 answers

3
Andrey Mikhaylov - lolmaus On BEST ANSWER

When you do record.save(), the following things happen (as of Ember Data 1.0.0-beta-19.1):

  1. You run record.save().
  2. The record tells the store to schedule its save operation: store.scheduleSave().
  3. Once per runloop cycle, the store flushes scheduled save operations: store.flushPendingSave().
  4. The store asks the record's adapter to perform the save: adapter.updateRecord().
  5. The adapter asks the record's serializer to convert the record into a JSON payload: serializer.serializeIntoHash.
  6. The adapter builds the URL: adapter.buildURL.
  7. The adapter performs the request to the backend.
  8. The store asks the serializer to convert the response from the server into data and push it into the store: serializer.extract() -> serializer.extractSave() -> serializer.extractSingle().
  9. The serializer runs the serializer.normalizePayload() which does nothing but you can override it to clean the payload.
  10. The serializer prepares the payload and pushes the resulting payload to the store.
  11. The store runs its store.didSaveRecord() method.
  12. The store triggers the didCommit event on the model.
  13. Finally, the promise returned by record.save() in item 1 resolves.

Some steps are missing in this list, I only highlighted important ones. I encourage you to follow the whole procedure in the sources, I gave you enough references.

Now to your question. I suggest that you override the serializer.extractSave() method. There you can convert your backend's payload into the Ember format and fiddle with it. Don't forget to call this.super() with all the arguments and the modified payload so that Ember actually pushes it to the store!