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

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

1个答案

1

When developing applications with the NestJS framework, it is often necessary to validate input data to ensure its correctness and security. Using class validators (such as class-validator) and Swagger (via the @nestjs/swagger module) can conveniently implement this functionality and clearly document API documentation. Below, I will illustrate how to use class validators and Swagger in a NestJS project to validate and display array data properties.

Step 1: Set Up Project Foundation

First, ensure that your NestJS project has the class-validator and @nestjs/swagger packages installed. If not, you can install them using the following command:

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

Step 2: Create DTO Classes

In NestJS, we typically use DTO (Data Transfer Object) classes to define and transfer data structures. In this example, we need to validate user-submitted order information, which includes multiple product items, each consisting of a product ID and quantity:

typescript
import { Type } from 'class-transformer'; import { IsArray, ValidateNested, IsInt, IsPositive, Min } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; class ProductItem { @ApiProperty({ description: 'Product ID' }) @IsInt() @IsPositive() productId: number; @ApiProperty({ description: 'Product Quantity', minimum: 1 }) @IsInt() @Min(1) quantity: number; } export class CreateOrderDto { @ApiProperty({ type: [ProductItem], description: 'Order items' }) @IsArray() @ValidateNested({ each: true }) @Type(() => ProductItem) items: ProductItem[]; }

In the above code, the ProductItem class defines the data structure for product items, ensuring productId is a positive integer and quantity is at least 1 using IsInt and IsPositive for productId, and IsInt and Min(1) for quantity. The CreateOrderDto class marks the items property as an array and uses ValidateNested and Type to ensure each element conforms to the ProductItem structure.

Step 3: Use DTO in Controller

In the corresponding controller, we receive and validate client-submitted data:

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: 'Create order', type: CreateOrderDto }) createOrder(@Body() createOrderDto: CreateOrderDto) { // Handle order creation logic here return 'Order created successfully!'; } }

In the createOrder method, the @Body() decorator automatically maps the request body data to a CreateOrderDto instance and performs validation.

Step 4: Configure Swagger

Ensure that Swagger is enabled in the NestJS module, typically configured in the main.ts file:

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();

Through the above steps, we not only effectively validate request data but also generate API documentation via Swagger, making API usage and testing more convenient.

2024年8月16日 09:33 回复

你的答案