mathematic-inc / ts-japi

A highly-modular (typescript-friendly)-framework agnostic library for serializing data to the JSON:API specification
Apache License 2.0
203 stars 16 forks source link

[FR] Runtime Serializer Resolver for Relator (support for heterogenous relationship types) #41

Open jaridmargolin opened 2 years ago

jaridmargolin commented 2 years ago

Is your feature request related to a problem? *

Currently, the Relator constructor assumes that there will be a single serializer class used for each relator. However, as we are building out a "SearchResultsSerializer", we would like to return a "result" relationship which may be one of several types. The fetch function of the relator will be smart enough to return the correct data based on the data passed to it, but there is no way to dynamically select the correct Serializer.

{
  relationships: {
    result: { "data": { "type": "people", "id": "9" } }
  }
}

or

{
  relationships: {
    result: { "data": { "type": "item", "id": "5" } }
  }
}

Ref: https://discuss.jsonapi.org/t/how-to-implement-a-search-api/35/3

Describe the solution you'd like*

It would be great if we could pass in a Serializer (current functionality) or a function that takes the data as the first parameter and returns a Serializer class to use.

Describe alternatives you've considered*

Another option could be to specify each possible type as a relator but it seems unnecessary to have to pass null relationships for every supported type:

{
  relationships: {
    people: null,
    item: { "data": { "type": "item", "id": "5" } }
  }
}

Additional context

I'll need to take a closer look at the code to ensure it wouldn't be a nightmare to implement, but happy to do the leg work on this if you agree with the API decisions and are willing to review/merge the work.