algoan / nestjs-components

A list of useful components for NestJS applications
https://www.algoan.com
253 stars 41 forks source link

[CLASS_TRANSFORMER] Allow to give fallback value to enum #834

Closed amarlankri closed 9 months ago

amarlankri commented 9 months ago

Description

Currently, it is possible to check that the value of a property is included in an enum definition using isEnum validator. Its behaviour is the following:

Most of the time, this behaviour is desired but it may be too strict in other use cases. For those cases, having the ability to provide a fallback value seems to be a good solution. The behaviour would be:

Solution proposed

Creating a new transformer EnumFallback which allows to provide a fallback function and the enum type. Here is an example of its usage:

export enum UserRole {
  ADMIN = 'ADMIN',
  READER = 'READER',
}

class UserDto {
  @EnumFallback({
    type: UserRole,
    fallback: (value: UserRole) => UserRole.READER // if the role is not "ADMIN" or "READER", then the role will be "READER". 
  })
  public role?: UserRole;
}

This solution is possible according to class transformer documentation. In addition, it would require to create a new library @algoan/nestjs-class-transformer as we did for class validators.

By the way, you should notice that if you use the transformer in conjunction with Nest validation and the whitelist option is enabled (see documentation), you will have to add the decorator @Allow too:

class UserDto {
  @EnumFallback({
    type: UserRole,
    fallback: (value: UserRole) => UserRole.READER
  })
  @Allow() // required if whitelist = true
  public role?: UserRole;
}

If this decorator is missing, then the enum property will be simply removed from the returned object.

FAQs

References

Close #833