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?
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!!
That's a PATCH
not a PUT
.
See https://www.rfc-editor.org/rfc/rfc5789
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With