joukevandermaas / saule

JSON API library for ASP.Net Web API 2.
https://joukevandermaas.github.io/saule
MIT License
76 stars 37 forks source link

Allow for self link generation for custom routes #231

Closed DtaggartMB closed 4 years ago

DtaggartMB commented 4 years ago

Reason

When doing a Post/Put for a single resource object using a custom route for example /location/{id}/rooms where a room was being created, the generated return self link would be generated as /locations/48/rooms/ rather then the expected /locations/48/rooms/{roomid}

POST /locations/48/rooms/

{ 
    "data" : 
    { 
        "type" : "rooms", 
        "attributes" : 
        { 
            "name" : "___hxLnCfZU60", 
            "capacity" : 100, 
            "description" : "Generated by automation using the v5 endpoint" 
        } 
   } 
}

Return

{
  "data" : {
    "type" : "rooms",
    "id" : "12684",
    "attributes" : {
      "name" : "___hxLnCfZU60",
      "capacity" : 100,
      "description" : "Generated by automation using the v5 endpoint"
    }
  },
  "links" : {
    "self" : "<url>/locations/48/rooms/"
  }
}

What we did was look to see if the returned resource was a collection type, if it isn't it would look for a ID to try to generate that self link. We used the override-able method BuildCanonicalPath to generate the link. If using the default logic the link would generate as /rooms/{id} which is the standard way if you don't have it stacked within another route. Since we do have a custom route our override method produces the correct output.

Now if we made a request to a get a collection of rooms. /locations/48/rooms/ the logic will default the self to the original requesting url/locations/48/rooms/