What options are there there for resolving nested resources in ngResource responses?
There have been some related questions about resolving endpoints for nested resource in ngResource, but this question is about when a REST response contains a second resource nested in the collection that is being queried, especially 1-to-1 mappings where you wouldn't have e.g. pets/<id>/owner
as its own resource.
Say there are two resources, Pets
and Owners
:
GET /pets:
[{
name: 'spark',
type: 'dog',
owner: '/owners/3/' # alternatively just '3' or the full object.
}]
As a developer, I sometimes want to query the Owner
resource as a whole, sometimes I want to query the Pet
resource and then I automatically want to resolve the owner
attribute into a resource instance.
This is my current solution:
.factory('Pet', function ($resource, Owner) {
var Pet = $resource('/pets/:id', {id: '@id'});
Pet.prototype.getOwner = function () {
return new Owner(this.owner); // or Owner.get({id: this.owner})
}
return Pet;
})
Problems here are many. There's integrity – for one. This implementation, I believe, allows for multiple instances of the same resource. Then there's practicality. You also have additional attributes to keep track of (owner
and getOwner()
, instead of just owner
; possibly setOwner
if you want to be able to save the model).
An alternative solution could be built on transformResponse
, but it would feel like a hack to include that in every resource that has a nested mapping.
Restangular.one('pets', 1).one('owner').get()
and that loads/pets/1/owner
.I am looking for a paradigm where there is one unique endpoint for each resource, so each owner would be accessible only from/owners/
, but at the same time it might be possible to embed an object in a response for a different resource. – Hepatitis