algoan / nestjs-components

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

[CLASS_VALIDATORS] Allow to give fallback value to enum validator #833

Closed amarlankri closed 11 months ago

amarlankri commented 11 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 validator IsEnumWithFallback which allows to provide a fallback function in addition to the enum type. Here is an example of its usage:

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

class UserDto {
  @IsEnumWithFallback({
    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 seems to be possible according to class validators documentation.

FAQs

qhdinh commented 11 months ago

In my opinion, a validator is supposed to only return validated or not. If you would like to return different values based on where the object is validated or not, it won't be a validator anymore. Your proposed feature seems more like a transformer to me. So I think it'd be better to use @Transform of class-transformer. https://github.com/typestack/class-transformer#additional-data-transformation And in that decorator, we use function isEnum() to determine if the object value belongs to enum or not and return corresponding result value.

amarlankri commented 11 months ago

The solution described in #834 has been chosen.