joukevandermaas / saule

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

Resource model relationships should support an optional 'include' parameter #126

Closed goo32 closed 7 years ago

goo32 commented 8 years ago

From my understanding Saule currently includes relationships by default. A nice enhancement would be to allow an optional include parameter on the association that would be respected on serialization.

eg.

In resource model...

`BelongsTo("Author"); // Default include = true``

Would be serialized to...

"relationships": {
  "author": {
    "links": {
      "self": "http://example.com/articles/1/relationships/author",
      "related": "http://example.com/articles/1/author"
    },
   "data": { "type": "people", "id": "9" }
  },
...
"included": [{
  "type": "people",
  "id": "9",
  "attributes": {
    "first-name": "Dan",
    "last-name": "Gebhardt",
    "twitter": "dgeb"
  }

While...

`BelongsTo("Author", false);``

Would be serialized to...

"relationships": {
  "author": {
    "links": {
      "self": "http://example.com/articles/1/relationships/author",
      "related": "http://example.com/articles/1/author"
    }
  },
joukevandermaas commented 8 years ago

I like this suggestion, and it ties in nicely to what I replied on #125. That said, I don't think a boolean is sufficient. As far as I can see, there are three options:

  1. Always include (also if the value is null or if the property does not exist on the model)
  2. Never include (always serialize a link even if the property has a value)
  3. Decide based on the value (a link if null, otherwise include it)

The third is the current behavior, and should remain the default.

goo32 commented 8 years ago

What about something like this?...

BelongsTo<AuthorResource>("Author"); // Default behaviour ie. ApiResource.ExcludeIfNull
BelongsTo<AuthorResource>("Author", ApiResource.Include);
BelongsTo<AuthorResource>("Author", ApiResource.Exclude);
joukevandermaas commented 8 years ago

Yes, I like the idea of an enum, probably named something like SideLoad or Include. Possible values should be:

  1. IfProvided (default)
  2. Always
  3. Never
yohanmishkin commented 8 years ago

Forgive me if I'm misunderstanding, but maybe this is best left to be decided by the actual web request using the include request parameter?

See here