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

How to use DTOs classes from another package for validation in NestJS?

1个答案

1

Step 1: Install Required Packages

First, ensure your NestJS project has the class-validator and class-transformer packages installed. These packages are commonly used for DTO validation.

bash
npm install class-validator class-transformer

Step 2: Import the DTO Class

Ensure you can import the DTO from the external package. Assume this external DTO class is named ExternalDTO and is part of the npm package external-package.

typescript
import { ExternalDTO } from 'external-package';

Step 3: Use the DTO in Controller

In your Controller, use the @Body() decorator to capture the incoming request body and apply the ExternalDTO class to automatically validate the data.

typescript
import { Controller, Post, Body } from '@nestjs/common'; import { ExternalDTO } from 'external-package'; @Controller('your-controller') export class YourController { @Post() async create(@Body() externalDto: ExternalDTO) { // Here, externalDto is already validated // ... return 'Success!'; } }

Step 4: Use Pipes for Validation

Ensure ValidationPipe is configured in the main.ts file or locally within your controller so that NestJS automatically applies validation rules from class-validator.

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()); await app.listen(3000); } bootstrap();

Alternatively, apply it to a specific controller or route:

typescript
import { Body, Controller, Post, UsePipes, ValidationPipe } from '@nestjs/common'; import { ExternalDTO } from 'external-package'; @Controller('your-controller') export class YourController { @Post() @UsePipes(new ValidationPipe()) async create(@Body() externalDto: ExternalDTO) { // ... } }

Example Scenario

Suppose you're developing an e-commerce platform and need to import the UserDTO class from a shared user management service. This service defines fields like username and password. Follow the steps above to import UserDTO and use it for validation in your user registration endpoint.

Summary

By following these steps, you can easily leverage DTO classes from other packages in your NestJS project to validate the structure and types of incoming request data, ensuring data correctness and security.

2024年8月16日 09:32 回复

你的答案