import { IsString, IsNumber, IsOptional, IsUUID, Min, Max } from 'class-validator';
import { Transform } from 'class-transformer';
export class QueryCollateralTypeDto {
@Transform(({ value }) => parseInt(value))
@IsNumber()
@IsOptional()
page: number;
@Transform(({ value }) => parseInt(value))
@IsNumber()
@IsOptional()
limit: number;
@IsString()
@IsOptional()
select: string;
}
我想设置页面和限制的默认整数值以及选择的字符串值(例如页面值为整数1,限制值为整数10,选择值为"field1,field2,…"(
Okey我找到了一个解决方案,我想你只是在DTO 中初始化变量
import { IsString, IsNumber, IsOptional, IsUUID, Min, Max } from 'class-validator';
import { Transform } from 'class-transformer';
export class QueryCollateralTypeDto {
@Transform(({ value }) => parseInt(value))
@IsNumber()
@IsOptional()
page: number = 1;
@Transform(({ value }) => parseInt(value))
@IsNumber()
@IsOptional()
limit: number = 10;
@IsString()
@IsOptional()
select: string = 'name,description';
}
您可以在服务和使用数据的函数中设置默认值,如下图所示。如果不向函数传递任何值,则会设置默认值。
exampleFunction(data: QueryCollateralTypeDto) {
const { page = 1, limit = 10, select = 'field1' } = data;
...
}
您必须使用ValidationPipe为控制器或方法添加选项transform-on-true(https://docs.nestjs.com/techniques/validation)
//at the controller level:
@Controller('some_controller')
@UsePipes(new ValidationPipe({ transform: true}))
export class SomeController {
constructor() {}
//or at the method level
@Post()
@UsePipes(new ValidationPipe({ transform: true}))
create(
@Body() someDto: SomeDto,
): Promise<someEntity> {
return this.service.create(someDto);
}