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

How to display properties of array data with class-validator and swagger nestjs

1 个月前提问
1 个月前修改
浏览次数6

1个答案

1

在使用NestJS框架进行应用开发时,经常需要对输入数据进行验证以确保数据的正确性和安全性。使用类验证器(如class-validator)和Swagger(通过@nestjs/swagger模块)可以很方便地实现这一功能,并且可以清晰地展示API文档。下面我将通过一个例子来说明如何在NestJS项目中使用类验证器和Swagger来验证和显示数组数据的属性。

Step 1: 设置项目基础

首先,确保你的NestJS项目已经安装了class-validator@nestjs/swagger这两个包。如果还没有安装,可以通过以下命令进行安装:

bash
npm install class-validator class-transformer @nestjs/swagger swagger-ui-express

Step 2: 创建DTO类

在NestJS中,我们通常会使用DTO(Data Transfer Object)类来定义和传输数据结构。在这个例子中,假设我们需要验证一个用户提交的订单信息,订单中包含多个商品项,每个商品项包括商品ID和数量:

typescript
import { Type } from 'class-transformer'; import { IsArray, ValidateNested, IsInt, IsPositive, Min } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; class ProductItem { @ApiProperty({ description: '商品ID' }) @IsInt() @IsPositive() productId: number; @ApiProperty({ description: '商品数量', minimum: 1 }) @IsInt() @Min(1) quantity: number; } export class CreateOrderDto { @ApiProperty({ type: [ProductItem], description: '订单中的商品项' }) @IsArray() @ValidateNested({ each: true }) @Type(() => ProductItem) items: ProductItem[]; }

在上述代码中,ProductItem 类定义了商品项的数据结构,使用IsIntIsPositive确保productId是正整数,IsIntMin(1)确保quantity至少为1。CreateOrderDto 类中的items属性标记为数组,并且使用ValidateNestedType确保数组中的每个元素都符合ProductItem的结构。

Step 3: 控制器中使用DTO

在相应的控制器中,我们接收和验证客户端提交的数据:

typescript
import { Body, Controller, Post } from '@nestjs/common'; import { ApiCreatedResponse } from '@nestjs/swagger'; import { CreateOrderDto } from './dto/create-order.dto'; @Controller('orders') export class OrdersController { @Post() @ApiCreatedResponse({ description: '创建订单', type: CreateOrderDto }) createOrder(@Body() createOrderDto: CreateOrderDto) { // 在这里处理订单创建逻辑 return 'Order created successfully!'; } }

createOrder方法中,通过@Body()装饰器自动将请求体中的数据映射到CreateOrderDto实例,并进行验证。

Step 4: 配置Swagger

确保在NestJS模块中启用了Swagger,通常在main.ts文件中配置:

typescript
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('Example API') .setDescription('The example API description') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api', app, document); await app.listen(3000); } bootstrap();

通过以上步骤,我们不仅实现了对请求数据的有效验证,还通过Swagger自动生成了API文档,使得API的使用和测试变得更加方便。

2024年8月16日 09:33 回复

你的答案