Search code examples
angularjsangular-resource

AngularJS $resource object doesn't provide an idempotent update method?


I've really be trying to wrap my head around this as much as possible, but having a very difficult time doing so. Maybe I'm missing the obvious.

Given a typical REST API (with an idempotent update method and a create method):

http://www.domain.com/api/clients           GET     // returns all clients
http://www.domain.com/api/clients           POST    // create a new  client
http://www.domain.com/api/clients/:id       GET     // returns single client
http://www.domain.com/api/clients/:id       PUT     // updates a single client - idempotent
http://www.domain.com/api/clients/:id       DELETE  // delete single client

If I create a standard resource with the following URL:

Client = $resource("http://www.domain.com/api/clients/:id")

Then I automatically get (where Client is the $resource and client is the returned entity):

Client.get()
Client.query()
Client.save()
client.$save()
client.$remove/delete()

The problem I have is by default there is no PUT method to save (typically used to identify idempotent updates).

Am I misunderstanding something or is this a deficiency in Angular's API? I would have expected the $save() to use a PUT and not a POST. The way it is currently structured, I have to create my own $update() method definition and then rely on the developer not to accidentally use the $save() method.

Am I structuring my API incorrectly? Should the REST API be structured differently?


Solution

  • You can simply specify the method in your resource like :

    app.factory('someFactory', ['$resource', function($resource) {
      return $resource('/api/:id', {
        id: '@id'
      }, {
      update: {
        method: 'PUT'
      },
      get: {
        method: 'GET'
      }
     });
    }]);
    

    but I totally agree with $save being an odd verb for create and not update. This guy does too and it looks like he made a way to dual purpose the save by simply extending the object and checking for an id.