typestack / class-transformer

Decorator-based transformation, serialization, and deserialization between objects and classes.
MIT License
6.66k stars 487 forks source link

feature: function support of options.discriminator.subTypes #1651

Closed buddh4 closed 1 month ago

buddh4 commented 7 months ago

Description

We currently can define discriminator types as follows:

@Type(() => Photo, {
    discriminator: {
      property: '__type',
      subTypes: [
        { value: Landscape, name: 'landscape' },
        { value: Portrait, name: 'portrait' },
        { value: UnderWater, name: 'underwater' },
      ],
    },
  })
  topPhoto: Landscape | Portrait | UnderWater;

This assumes that we know all subTypes at build time. There is no way (I've found) to add discriminator types at runtime (other that passing the subTypes array around).

Furthermore the transformer throws an error when using instanceToClass and the discriminator is not contained in the subTypes. Maybe a strict or fallbackToDefault configuration would be nice.

Proposed solution

It would be great if you could also use a function for the subType option as follows:

@Type(() => Photo, {
    discriminator: {
      property: '__type',
      strict: false,
      subTypes: (subType: string) => getTypeOfPhoto(subType),
    },
  })
  topPhoto: Landscape | Portrait | UnderWater;

I'm happy to contribute in case this feature is desired. I did a quick look and it seems this would only require minor changes here and here.

diffy0712 commented 2 months ago

Hello @buddh4,

could you please give some use cases for dynamic subTypes? I assume getTypeOfPhoto would do the same as the map, isn't it? I am not sure when this would be useful.

Thank you

diffy0712 commented 1 month ago

Closing as invalid, because of inactivity. If you want to continue this discussion, feel free to comment on this issue.

github-actions[bot] commented 3 weeks ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.