首页 > 解决方案 > NestJS 根据类型将正文参数强制为值

问题描述

首先,我只是问这个,因为我没有找到适合这种情况的答案。我也刚开始学习 NestJS。

我有以下声明:

// Type definition of options
type Gender = "Male" | "Female";

// DTO
export class User {
    ...
    gender: Gender;
}

// Inside controller
...
@Post()
registerUser(@Body() data: User) {
    console.log(data.gender);
}
...

不幸的是,如果它在正文中将性别设置为“未知”,它将是 data.gender 的值,即使它不在允许的值区间内。我想将值限制为类型定义中唯一可用的值。我已经看到了有关如何在枚举中执行此操作的示例,但没有看到关于类型的示例。是否可以使用类型来限制它们?

标签: typescriptnestjstypescript-typings

解决方案


npm i --save class-validator class-transformer

在 main.ts 中进行更改

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());  <= add this
  await app.listen(3000);
}
bootstrap();

像这样尝试

import { IsDefined, IsIn, IsNotEmpty } from 'class-validator';

// DTO
export class User {
    ...

    @IsDefined()
    @IsNotEmpty()
    @IsIn(['Male','Female'])
    gender: Gender;
}

// Inside controller
...
@Post()
registerUser(@Body() data: User) {
    console.log(data.gender);
}
...

推荐阅读