Friday 30 October 2020

Restangular PUT without an identifier

I've been using Restangular for a long time now, but for one problem I could never find a clean solution.

Let's say I have a rest endpoint like this:

/rest/team/123 -> gives me the Team.
/rest/team/123/season/7 -> gives me the season-specific data for team 123 in Season 7

the seasonTeam looks like this:

{
  coachId: 15,
  imageURL: '',
}

my code looks something like this:

var resource = team.resource.one('season', seasonId);
resource.get().then(function(to) {
    $scope.seasonTeam = to;
});

and at a later point:

$scope.seasonTeam.coachId = ... ;
$scope.seasonTeam.put();

I purposely didn't include an id in my object model. Now when I run this, I get an error because Restangular is trying to put it to /rest/team/123/season instead of /rest/team/123/season/7

I hoped that Restangular would use the same URL from the get() function to use in the put().

So I added an id:

{
  id: 7,
  coachId: 15,
  imageURL: '',
}

and now it works nicely. But it bugs me that the id in the object is not really the object's id, but the season.id . The server source code just got incredibly ugly.

I could live with:

{
  seasonId: 7,
  coachId: 15,
  imageURL: '',
}

but the put() doesn't know that it should use the seasonId for the resource path.

I'm looking for a clean solution fo this, maybe something like:

var resource = team.resource.one('season', seasonId);
resource.get().then(function(to) {
    to.tellRestangularToUseThisAsIdForPath('seasonId');
    $scope.seasonTeam = to;
});

any good suggestions? and I'd also love to understand why RestAngular doesn't use the same URL for get() and put()



from Restangular PUT without an identifier

No comments:

Post a Comment