Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to PUT only some fields with Restangular?

Let's say I have a resource with several fields, and some of them are read-only. Or maybe they belong in different use cases that I would like to handle differently on the server.

For instance, my bing resource looks like this:

{id: 1,
 foo: "A", 
 bar: "B", 
 createdAt: "2013-05-05"}

I would like to get Restangular to PUT only some fields, executing requests like:

PUT /bing/1 {foo: "A"}
PUT /bing/1 {bar: "B"}
PUT /bing/1 {foo: "A", bar: "B"}

What I do not want to do is:

PUT /bing/1 {id: 1, foo: "A", bar: "B", createdAt: "2013-05-05"}

How can I achieve it?

like image 330
Konrad Garus Avatar asked Aug 08 '13 10:08

Konrad Garus


3 Answers

I'm the creator of Restangular.

@Nicholas is absolutely right :). That's a PATCH and not a PUT. And Restangular does support it :).

elem.patch({foo: 2}) would be the way to go if elem is already a restangularized object.

Hope this helps!!

like image 63
mgonto Avatar answered Nov 10 '22 08:11

mgonto


That's a PATCH not a PUT.

See https://www.rfc-editor.org/rfc/rfc5789

like image 6
Nicholas Shanks Avatar answered Nov 10 '22 06:11

Nicholas Shanks


One way to do this is to pass the entire object to the patch method, including all the fields that you don't want to send to the backend, and then use a request interceptor to delete any unwanted fields before the request is sent.

For example, to always delete the field createdAt from any patch request you could do something like

app.config(function(RestangularProvider) {
  RestangularProvider.setRequestInterceptor(function(element, operation, route, url) {
    if (operation === 'patch') {
      delete element.createdAt;
      return element;
    } 
  });
});

To learn more about request interceptors see the documentation on setRequestInterceptor

like image 2
aeneaswiener Avatar answered Nov 10 '22 08:11

aeneaswiener