乐闻世界logo
搜索文章和话题

How to automatically add type validation decorators to Nestjs dto

2 个月前提问
2 个月前修改
浏览次数32

1个答案

1

在 NestJS 中,我们通常使用类和装饰器来定义 DTO(Data Transfer Object),以确保API接收到的数据类型和结构正确。为了自动向 DTOs 添加类型验证装饰器,我们可以利用类验证器(class-validator)库,该库提供了许多用于数据验证的装饰器。以下是如何实现的步骤和示例:

步骤 1: 安装依赖

首先,你需要安装 class-validatorclass-transformer。这两个库能够帮助你在运行时自动验证和转换类的属性。

bash
npm install class-validator class-transformer

步骤 2: 创建 DTO 类并添加装饰器

在 DTO 类中,你可以使用 class-validator 提供的装饰器来添加不同的验证规则。例如,如果你想验证一个用户注册接口的数据,可以创建一个 UserDTO 类如下所示:

typescript
import { IsNotEmpty, IsEmail, Length } from 'class-validator'; export class UserDTO { @IsNotEmpty({ message: '用户名不能为空' }) username: string; @IsEmail({}, { message: '请提供有效的邮箱地址' }) email: string; @IsNotEmpty({ message: '密码不能为空' }) @Length(8, 20, { message: '密码长度应在8到20字符之间' }) password: string; }

步骤 3: 在控制器中使用 DTO

在控制器中,你需要使用 @Body() 装饰器来获取请求体,并指定使用的 DTO 类型。NestJS 会自动应用 DTO 中定义的验证规则。

typescript
import { Controller, Post, Body } from '@nestjs/common'; import { UserDTO } from './dto/user.dto'; @Controller('users') export class UserController { @Post('register') async register(@Body() userDto: UserDTO) { // 在这里 userDto 已经经过验证 return 'User registered'; } }

步骤 4: 启用全局验证管道

为了让 NestJS 处理 DTO 中的验证装饰器,你需要在你的应用程序中启用全局验证管道。可以在你的主模块或启动文件中添加以下配置:

typescript
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ValidationPipe } from '@nestjs/common'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true })); await app.listen(3000); } bootstrap();

结论

通过使用 class-validatorclass-transformer,你可以轻松地向 NestJS 应用中的 DTO 类自动添加类型验证装饰器。这种方法简化了数据验证逻辑的实现,并有助于保持代码的整洁和一致性。如果验证失败,NestJS 会自动抛出异常,返回客户端相关的错误信息。这样可以大大提高开发效率,也使得代码更容易维护和测试。

2024年7月24日 13:48 回复

你的答案