Question

I am writing a Backbone application which should interface to a REST API.

My problem arises when a user deletes a model that has already been deleted by someone else. In my opinion, the backend should just return success (200), as the model is deleted anyway. But the people developing the server side have a different opinion, hence what I get is a 404. For comparison, when the request actually fails - hence the model is still alive - the response code is 400, or possibly 401 for authorization issues.

Since I get an error, I actually do not remove the model. What I am trying to do is modifying this behaviour: if I get a 404 error while deleting a model, it should be treated as success. But I am not really sure what is the most convenient way to handle this.

Ideally I would like to avoid putting this logic inside model.destroy. This would lead to a repetition. I could put this inside a destroy method of a superclass, but models override this method anyway, each one with its own logic, so it gets messy. I would prefer that at this point the model.destroy methods received a success, not knowing that the actual response was a 404.

On the other hand, I am not sure how to put this logic inside Backbone.sync, short of rewriting the whole function.

What is the most transparent way to transform all 404 responses to DELETE requests into success?

Était-ce utile?

La solution

It's a hack, but should do the trick:

model.destroy({
    error: function(model, resp, options) {
        if (resp.status == 404) {
            resp.status = 200; 
            options.success(model, resp);
        }
     }
})

Btw, as of Backbone 0.9, destroy() and create() are optimistic.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top