Validate DTO in controller when passing data to service

Viewed 1355

I am trying to insert a validation into PUT request(to update some data stored in MongoDB):

DTO:

export enum reportFields {
    'startDate',
    'targetDateOfCompletion',
    'duration',
}


export class updateScheduleDto {
    @IsOptional()
    @IsString()
    readonly frequency?: string;

    @IsOptional()
    @IsArray()
    @IsEmail({}, { each: true })
    @IsString({ each: true })
    readonly emails?: string[];

    @IsOptional()
    @IsEnum(reportFields, { each: true })
    @IsArray()
    @IsString({ each: true })
    readonly reportFields?: string[];

    @IsOptional()
    @Type(() => Number)
    @IsNumber()
    updatedAt?: number;
}

Controller:

@Put('reports/:id/schedule')
async updateScheduleData(
    @Param('id') id: string,
    @Body(new ValidationPipe()) updateData: updateScheduleDto,
) {
    return this.reportService.updateScheduleData(id, updateData);
}

Service:

 async updateScheduleData(id: string, updateData: updateScheduleDto) {
        try {
            updateData.updatedAt = this.utils.getCurrentTime();
            const newData = await this.reportScheduleModel.findByIdAndUpdate(
                id,
                updateData,
                {
                    new: true,
                },
            );

            console.log(`Data has been updated to ${newData}`);
            return newData;
        } catch (error) {
            throw new Error('>>>' + error);
        }
    }

But the validation not working over the keys. If I pass a non-valid key(like below) in the body object, even then the program executes without any error, how do I fix this? What am I missing?

{
    "emaaaalls":["randomemail123@gmail.com"]
}
2 Answers

You need to pass the options { forbidUnknownValues: true } to the ValidationPipe. This will make class-validator throw an error when unknown values are passed in. You can read through the options here

Related