How to handle non standard/unexpected server response in custom REST Serializer?


#1

Hi,

I have a custom REST Adapter/Serializer. The server response of POST/PUT/DELETE commands doesn’t always include the id of the respective model and only contains an attribute when the update/creation happened:

PUT: { “updatedAt”: “2011-08-21T18:02:52.248Z” }

POST: { “createdAt”: “2011-08-20T02:06:57.931Z”, “objectId”: “Ed1nuqPvcm” }

How can I merge the response into the existing model?

Thank you Philipp


#2

I have a similar problem. In my case, I also have a customized RESTSerializer in which I rewrote the extractSingle function for a single record, for example a post.

Now I want to delete a record, I use for example post.deleteRecord() and then post.save(), ember would send a DELETE request to the server and successfully delete the record. But after the record has been deleted, the server will response with an object, in my case that is { status: true }, when this object is returned, ember treats it as a payload and call extractSingle function again, but obviously this will cause an error, because this object is not a post and the format is not what emberData expects.

I’m wondering is there a way to avoid this issue or how could I handle unexpected response if I have a customized serializer.


#3

I’m having an issue with this as well. When deleting a record my serializer received the payload, which in my case looks like so:

{
   "result": {}
} 

and no matter what I pass to the serializer function, I get errors.

if I return {status: true} as suggested above by bboybeam than I get the following error:

Error: Assertion Failed: An adapter cannot assign a new id to a record that already has an id. <(subclass of DS.Model):ember704:PROJECT_ID_REPALCED:g14292> had id: PROJECT_ID_REPLACED:g14292 and you tried to update it with null. This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.

#4

Hey @eli_sklar, sorry for replying so late as I haven’t toughed my project for several weeks. Today I fixed this issue, as I said the API returned { status: true } and it gave me the error you mentioned, this is because ember data expects an id from the response object even if we are deleting it.

So what I did is after the record has been deleted and the response is returned from the server, if the request is deleting record, I just put the previous id back to the response in the serializer, to be exact in the extractSingle function:

extractSingle: function(store, type, payload, id, requestType) {

      var post_payload = {};

      post_payload[type.typeKey] = payload;

      if (requestType === "deleteRecord") {
        post_payload[type.typeKey].id = id;
      }

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

by doing this I have solved this problem. But it is weird though that ember still expects an id even if for deleting.