0

I am looking for a correct way to handle a data type that can be obtained via different resource urls. Please see code examples below:

storeServices.factory('Booklist', ['$resource',
    function($resource){
        return $resource('http://some.domain.com/api/stores/:storeId/booklists/',
            {}, {
            query: {method:'GET', params:{storeId:'@storeId'}, isArray:true}
        });
    },
]);

But separately there is another API for getting just the list of books without the need to specify storeId. Eg:

http://some.domain.com/api/booklists/

Should I create a different factory with different name or is there a better/correct way? Thanks in advance to any replies.

Bolto Cavolta
  • 413
  • 1
  • 8
  • 16

1 Answers1

0

It's definitely possible to call these two different endpoints using same $resource, but it's questionable if these two resources/endpoints are of same type (in order to be consumed using same $resource factory).

To accomplish this you need to parameterise your nested resources, so that the full url can be constructed dynamically in run-time:

PLUNKER

app.controller('MainController', function($scope, Booklist) {

  // Sends request to http://some.domain.com/api/stores/1/booklists/
  $scope.withStoreId = Booklist.query({storeId: 1, level1: 'stores'});

  // Sends request to http://some.domain.com/api/booklists/
  $scope.withStoreId = Booklist.query();

});

app.factory('Booklist', ['$resource',
  function($resource){
    return $resource('http://some.domain.com/api/:level1/:storeId/booklists/',
      {}, {
      query: {
        method:'GET', 
        params: {
          storeId: '@storeId'
        }, 
        isArray: true
      }
    });
  }
]);
Stewie
  • 60,366
  • 20
  • 146
  • 113
  • Thanks for the quick response. One more question, in your code, should "params: {storeId: '@storeId'}" also include level1:'@level1'? – Bolto Cavolta Feb 13 '14 at 23:16
  • That's not needed because `level1` is not something that you will find inside your `booklist` objects. – Stewie Feb 13 '14 at 23:41
  • Thanks. I am still new to ng so please bear with me. I was under the impression that parameters inside a resource, eg: ../:level1/:storeId/... get their values from the params:{storeId: '@storeId', ...}. Now I think I actually don't understand how it works. So is it that params:{} should have attributes that belong to the return objects? – Bolto Cavolta Feb 14 '14 at 01:15
  • See [What is @id as passed to $resource?](http://stackoverflow.com/questions/17559515/what-is-id-as-passed-to-resource). – Stewie Feb 14 '14 at 08:20