export class MongoIDDto { @ApiProperty({ description: 'Id', required: true, type: String, default: '61d9cfbf17ed7311c4b3e485', }) @IsMongoId() @IsString() id: string;}
export class PaginateQueryDto<T> { @IsOptional() limit: number; @IsOptional() page: number; @Allow() offset: number; @IsOptional() sort: string | Record<string, 'asc' | 'desc' | 1 | -1>; @IsOptional() select: string | Record<string, 0 | 1>; @IsOptional() @IsObject() filters: Record<string, string>; @IsOptional() @ValidateNested() @Type(() => Object) params: T;}
I have this DTO which has a property that is based on another DTO. If I implement it as follows:
async findAll(@Query() query: PaginateQueryDto<MongoIDDto>) { console.log(query, '----------------query'); ...}
The result is:
{ limit: 5, page: 2, offset: 5, sort: { color: 'asc', name: 1, age: -1 }, select: { name: 1 }, filters: { name: 'SomeName' }, params: { id: 'someExtraProperty' }} ----------------query'
I expect the nested DTO validation is applied and responds with an error if the id property does not contain a value of type mongoId.
This should return an error:
{ limit: 5, page: 2, offset: 5, sort: { color: 'asc', name: 1, age: -1 }, select: { name: 1 }, filters: { name: 'SomeName' }, params: { id: 'someExtraProperty' }} ----------------query'
This should pass the validation:
{ limit: 5, page: 2, offset: 5, sort: { color: 'asc', name: 1, age: -1 }, select: { name: 1 }, filters: { name: 'SomeName' }, params: { id: '65fb3a13a4721100124332eb' }} ----------------query'
How can I validate the nested DTO in NestJS with class-validator?