rrousselGit/freezed

Allow N:1 mapping of union keys to union constructor

Open

#681 opened on Jun 6, 2022

 (2 comments) (6 reactions) (1 assignee)Dart (300 forks)github user discovery
enhancementgood first issue

Repository metrics

Stars
 (2,177 stars)
PR merge metrics
 (PR metrics pending)

Description

Is your feature request related to a problem? Please describe.

From what I have seen, union constructors map 1:1 with a union key. There are cases where I'd like to be able to have multiple union keys map to the same union constructor.

To support this use-case in the past I have duplicated the union class constructor with the alternate union key. This works, but it becomes extremely verbose and repetitive and creates hard-to-maintain freezed classes. For example, if you want to change one property you have to make sure all N duplicated constructors get updated in the same way

It would be ideal if union keys could map N:1 to union constructors such that this duplication were not necessary.

Bonus: Would be great if you could 'extend' a particular union constructor whereby it would automatically inherit the properties of a particular constructor and allow you to add additional properties to it. In the past I've had to similarly copy/paste the entire constructor just to add 1-2 additional properties. I know this could be solved via data modelling but that's not always possible when you're consuming a 3rd party api

Describe the solution you'd like Perhaps an approach like this may be ideal for maintaining backwards compatibility

  @JsonSerializable()
  @FreezedUnionValue('UNION_KEY_1')
  @FreezedUnionValue('UNION_KEY_2')
  @FreezedUnionValue('UNION_KEY_3')
  const factory MyObject.someUnionCase({
    required String id,
    required String name,
  }) = _MyObject;

Alternatively adding a new decorator could also work

  @JsonSerializable()
  @FreezedUnionValues([
     'UNION_KEY_1', 
     'UNION_KEY_2', 
     'UNION_KEY_2'
  ])
  const factory MyObject.someUnionCase({
    required String id,
    required String name,
  }) = _MyObject;

Describe alternatives you've considered As described above I've previously duplicated the union cases which is not ideal as it creates a lot of boilerplate and makes map(...) functions duplicative unnecessarily. It also leads to a lot more generated code which could be avoided entirely if multiple keys could just map to a single union case

Additional context Add any other context or screenshots about the feature request here.

Contributor guide