Partial Updates (aka PATCH) using a $resource based service?

Erik picture Erik · Oct 8, 2013 · Viewed 10.2k times · Source

We're building a web application using Django/TastyPie as the back-end REST service provider, and building an AngularJS based front end, using lots of $resource based services to CRUD objects on the server. Everything is working great so far!

But, we would like to reduce the amount of data that we're shipping around when we want to update only one or two changed fields on an object.

TastyPie supports this using the HTTP PATCH method. We have defined a .diff() method on our objects, so we can determine which fields we want to send when we do an update. I just can't find any documentation on how to define/implement the method on the instance object returned by $resource to do what we want.

What we want to do is add another method to the object instances, (as described in the Angular.js documentation here) like myobject.$partialupdate() which would:

  1. Call our .diff() function to determine which fields to send, and then
  2. Use an HTTP PATCH request to send only those fields to the server.

So far, I can't find any documentation (or other SO posts) describing how to do this, but would really appreciate any suggestions that anyone might have.

thank you.

Answer

iPirat picture iPirat · Apr 28, 2014

I would suggest using

update: {
    method: 'PATCH',
    transformRequest: dropUnchangedFields
}

where

var dropUnchangedFields = function(data, headerGetter) {

    /* compute from data using your .diff method by  */
    var unchangedFields = [ 'name', 'street' ];

    /* delete unchanged fields from data using a for loop */ 
    delete data['name'] ;
    delete data['street'];

    return data;

}

PS: not sure from memory, whether data is a reference to your resource of a copy of it, so you may need to create a copy of data, before deleting fields

Also, instead of return data, you may need return JSON.stringify(data).


Source (search for "transformRequest" on the documentation page)