joukevandermaas / saule

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

Fixed attributes serialization for included objects #242

Closed sergey-litvinov-work closed 4 years ago

sergey-litvinov-work commented 4 years ago

Hi Jouke,

Looks like as part of #238 there was introduced a new issue. If ApiResource has relationship and a caller requested ?include=some then it will return that object but all attributes in the included object would be null. It happens as that PR filters out properties that aren't in the current ApiResource but in case of Included that code still searches in the current ApiResource.

i updated it and now it creates serializer based on ApiResource from the ResourceGraphNode so it might be different depending on the object. I also added caching in Dictionary as DefaultContractResolver (and our inheritor SourceContractResolver) caches properties that it got from the Type but only as part of that instance so we can't recreate it each time.

i also used regular Dictionary and not ConcurrentDictionary as i'm not sure that this code can be executed in parallel Also updated one existing unit test to cover that scenario (just to validate that all attributes in the included object are present)

Before the fix the output of that test would be

{
  "data": {
    "type": "person",
    "id": "123",
    "attributes": {
      "first-name": "Lisabeth",
      "last-name": "Summers",
      "age": 7,
      "address": {
        "street-name": "6th Street",
        "zip-code": "66616"
      }
    },

...

  "included": [
    {
      "type": "corporation",
      "id": "456",
      "links": {
        "self": "http://example.com/api/corporations/456/"
      },
      "attributes": {
        "name": null,
        "number-of-employees": null,
        "location": null
      }
    },
    {
      "type": "car",
      "id": "12",
      "links": {
        "self": "http://example.com/api/cars/12/"
      },
      "attributes": {
        "model": null
      }
    }
  ]
sergey-litvinov-work commented 4 years ago

Thanks!