typescript - 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 的值,即使它不在允许的值区间内。我想将值限制为类型定义中唯一可用的值。我已经看到了有关如何在枚举中执行此操作的示例,但没有看到关于类型的示例。是否可以使用类型来限制它们?
解决方案
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);
}
...
推荐阅读
- terraform - terraform如何在for_each中使用条件if进入地图对象
- java - 查找数组中的最小峰值元素
- python - 在centos 7上安装tryton以获得gnu health,但我无法运行gnuhealth客户端和tryton客户端
- sql - 如何获得第二大列值和列名
- reactjs - 在另一个项目中将 git repo 作为包安装
- ios - 如何在 Testflight App 中直接进行深度链接构建
- javascript - 禁用嵌套 div 元素的单击事件,直到 setTimeout 结束
- python - Django urlpatterns 问题
- azure-synapse - 查询 Synapse Analytics 中所有表的大小
- c++ - 如何在 unordered_map 中使用向量变体作为键?