Is there a way to set the execution order of decorators when describing a DTO class in NestJS using class-validator
and class-transformer
packages ?
Following code fails when the value of foo
is set to null
with the error:
Expected a string but received a null
@IsOptional()
@IsString()
@IsByteLength(1, 2048)
@Transform(({ value }) => validator.trim(value))
@Transform(({ value }) => validator.stripLow(value))
foo: string;
Even though I have a isString
decorator that should check that indeed a string was passed and must already fail to not pass the execution to the @Transform
decorators, but it didn't fail.
Class-Validator works based on classes. Request payloads that come into the server are just plain JSON objects to start off with. To change this behaviour, Nest has to first call plainToClass
from class-validator
if you're using its ValidationPipe
. Because of this, the @Transform()
decorators take precedence over the other class-validator decorators, and are acted upon first. You could get around this by using multiple pipes, or possibly providing default values for the @Transform()
decorator, but what is happening is the intended effect.