Skip to content

Support mixed types in HasMany relationship #215

Closed
@hpawe01

Description

@hpawe01

A HasMany relationship (e.g. books: Book[]) does not allow mixed types (e.g. CrimeBook, NovelBook), even if they extend the same expected HasMany type (Book).

Problem
In this line, the type of the first element in the relationship is checked against all other types.

const relationshipType: string = isJsonApiModel ? objects[0].modelConfig.type : '';

Example
I have

@HasMany()
books: Book[];

and the models

@JsonApiModelConfig({
  type: 'crimeBooks',
  modelEndpointUrl: 'books'
})
export class CrimeBook extends Book {...}

@JsonApiModelConfig({
  type: 'novelBooks',
  modelEndpointUrl: 'books'
})
export class NovelBook extends Book {...}

Possible solution 1
Collect modelEndpointUrl or type of all relationship items and check if there is only one unique. This way, even if the type of the items differ (crimeBooks or novelBooks), if the modelEndpointUrl is the same (books), all should be fine.

Possible solution 2
Check, if all relationship items are instances of the model, that the HasMany attribute expects (Book).

I will create a pull request for solution 1, but I am not sure if solution 2 would be more clean (Although only type and modelEndpointUrl are relevant, when talking to the server, and not the Typescript type of the HasMany attribute).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions