Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update Restangular model object with server response?

My POST and PUT return the current state of entity as seen on the server. How can I tell Restangular to update its model object after the server call?

Just in case - why? Because during save/update the server may have calculated some fields. Because there may have been concurrent updates by other clients and I want to make sure that the client that is currently updating is up to date.

So far I only found this:

var res = {foo: "bar"};
var cb = function(response) {
    $.extend(res, response);
}
// POST / create
Restangular.all("resource").post(res).then(cb);

// PUT / update
res.put().then(cb);

It seems so dirty and common at the same time that I suspect there must be a better way.

EDIT

The code above only demonstrates two distinct actions. My goal is not to send update to server after creating the entity, but updating state on client. Synchronizing state with server, if you will.

When I POST an object:

var res = {foo: "bar"};
Restangular.all("resource").post(res);

Server response has body with:

{"foo": "bar", "id": 15}

... then I would like Restangular to update and restangularize the res object automatically, so it has the ID, can be put() etc.

Now a different / complementary scenario. When I PUT a Restangular object:

var res = Restangular.one("resource", 15).get();
// returns {foo: "bar", id: 15}
res.put();

The server always replies with the current state of the object, which may be:

{"foo": "buzz", "id": 15}

... so I would like Restangular to update res automatically after this PUT.

like image 939
Konrad Garus Avatar asked Aug 01 '13 07:08

Konrad Garus


1 Answers

I'm the creator of Restangular.

If I understand you correctly, you want to first do the post, and then do the put? In that case you could do something like:

var res = {foo: 'bar'};
Restangular.all('resource').post(rest).then(function(response) {
    res = response;
   res.put()
})

I don't know if I understood correctly.

Hope it works

like image 140
mgonto Avatar answered Oct 22 '22 16:10

mgonto