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:
If the value is one of the literal value of the enum, then the object is validated
Otherwise, throw an error
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:
If the value is one of the literal value of the enum, then the value is kept
Otherwise, return a default value of the enum
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
Why not providing a fallback function rather than just a value?
As a developper, you will probably want to add logs when the fallback is called and have more complex logic in the fallback. Returning a value wouldn't allow this.
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: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:If this decorator is missing, then the enum property will be simply removed from the returned object.
FAQs
References
Close #833