pap*_*lon 14 javascript node.js typescript nestjs
当查询为空时,有没有办法使用默认值?
如果我有以下 DTO 查询:
export class MyQuery {
  readonly myQueryItem: string;
}
我的请求不包含查询,那么myQuery.myQueryItem 将是未定义的。我如何使它具有默认值?
Kim*_*ern 24
您可以直接在 DTO 类中设置默认值:
export class MyQuery {
  readonly myQueryItem = 'mydefault';
}
您必须实例化该类,以便使用默认值。为此,您可以例如将ValidationPipe与选项一起使用transform: true。如果该值由您的查询参数设置,它将被覆盖。
@Get()
@UsePipes(new ValidationPipe({ transform: true }))
getHello(@Query() query: MyQuery) {
  return query;
}
1) 管道应用于您的所有装饰器,例如@Body(), @Param(),@Query()并且可以转换值(例如ParseIntPipe)或执行检查(例如ValidationPipe)。
2)ValidationPipe内部使用class-validator和class-transformer验证。为了能够对您的输入(纯 javascript 对象)执行验证,它首先必须将它们转换为带注释的 dto 类,这意味着它会创建您的类的一个实例。通过设置transform: true,它将自动创建 dto 类的实例。
示例(基本上是如何工作的):
class Person {
  firstname: string;
  lastname?: string = 'May';
  constructor(person) {
    Object.assign(this, person);
  }
}
// You can use Person as a type for a plain object -> no default value
const personInput: Person = { firstname: 'Yuna' };
// When an actual instance of the class is created, it uses the default value
const personInstance: Person = new Person(personInput);
| 归档时间: | 
 | 
| 查看次数: | 14881 次 | 
| 最近记录: |