class-transformer
class-transformer copied to clipboard
fix: Transform is not called for fields not passed in request body
Description
I am trying to add a field to request payload before validating using Transform, but It's not executed if the field is not present in the request payload
Code
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString } from "class-validator";
import { Transform, TransformFnParams } from "class-transformer";
export class ReqDTO {
@ApiProperty({})
@Transform(({ value }: TransformFnParams) => value?.trim())
@IsString()
@IsNotEmpty()
first_name: string;
@ApiProperty({})
@Transform(({ value }: TransformFnParams) => value?.trim())
@IsString()
@IsNotEmpty()
last_name: string;
@ApiProperty({ readOnly: true })
@Transform(({ value }) => {
console.log('Executing Transformer for testing field:', value);
return value;
})
generated_field: string;
}
The transformer is not executing for the below payload, but if passed generated_field, It executes.
{
"first_name": "Rohit",
"last_name": "Khatri"
}
Expected behavior
The Transform should be executing even if the field is not passed in the request body
Actual behavior
Transform decorator not executing if field is not passed in the payload
Same problem here
Same problem here - any solution yet?
Hello @rohitkhatri ,
If you have 'exposeUnsetFields' set to true on the plainToInstance method call, you can add an additional @Expose decorator on top of your property.
In you case:
@ApiProperty({ readOnly: true })
@Expose()
@Transform(({ value }) => {
console.log('Executing Transformer for testing field:', value);
return value;
})
generated_field: string;
Hope this helps.