beam-community / jsonapi

JSON:API Serializer and Query Handler for Elixir
https://hex.pm/packages/jsonapi
MIT License
495 stars 78 forks source link

Include NotLoaded relationships #288

Closed TylerPachal closed 1 year ago

TylerPachal commented 1 year ago

The Problem

Currently, it is not possible to view any information about a relationship unless you include it:

GET  /foobar/25
{
  "data": {
    "attributes": {...},
    "id": "25",
    "links": {
      "self": "https://example.com/foobars/25"
    },
    "relationships": {}, // <----- This is always empty
    "type": "foobars"
  }
}

And when you do include, it can be expensive as it triggers extra queries.


This PR

We can attach information we have about a relationships, like the id, without needing to include anything or perform any additional DB queries:

GET  /foobar/25

{
  "data": {
    "attributes": {...},
    "id": "25",
    "links": {
      "self": "https://example.com/foobars/25"
    },
    "relationships": { // <---- There is now data here about the relationship
      "foo": {
        "id": "354",
        "type": "foos"
      }
    },
    "type": "foobars"
  }
}

This is possible because even though the Foobar model would have a NotLoaded value for foo, there should still be a foreign key present on the model that we can use to populate the ID and links:

%Foobar{
  foo_id: 354, # <--- We can use this, even though the foo is not loaded
  foo: #Ecto.Association.NotLoaded<association :foo is not loaded>
}

Discussion Points: