class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

fix: Transform is not called for fields not passed in request body

Open rohitkhatri opened this issue 2 years ago • 3 comments

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

rohitkhatri avatar Aug 17 '23 02:08 rohitkhatri

Same problem here

JoseJavierSA avatar Sep 25 '23 13:09 JoseJavierSA

Same problem here - any solution yet?

ma-sommer avatar May 02 '24 15:05 ma-sommer

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.

diffy0712 avatar May 05 '24 20:05 diffy0712