DTO และไปป์ตรวจสอบข้อมูล
นำออบเจ็กต์ถ่ายโอนข้อมูล (DTO) มาใช้ และใช้ไปป์ตรวจสอบข้อมูลเพื่อให้แน่ใจว่าข้อมูลคำขอขาเข้าตรงตามเกณฑ์ที่กำหนด
DTO และไปป์ตรวจสอบข้อมูล เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน NestJS Enterprise Backend APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Data Transfer Objects?
When building APIs, your application receives data from users. This data needs to be structured and safe.
Data Transfer Objects (DTOs) are plain classes that define the expected shape of the data coming into your application (e.g., from a request body) or going out (e.g., as a response).
Using DTOs helps with:
- Clarity: Clearly shows what data is expected.
- Consistency: Ensures data adheres to a specific format.
- Security: Prevents unexpected or malicious data from being processed.
Defining a Simple DTO
A DTO is essentially a TypeScript class with properties that match the data you expect. It's a blueprint for your data.
Here's a basic example for creating a new product:
export class CreateProductDto {
name: string;
description: string;
price: number;
}DTOs in NestJS Context
In a NestJS application, you'll typically create DTO files in a dto folder within your module (e.g., src/products/dto/create-product.dto.ts).
These classes are then used in your controllers to type the incoming request body.
import { Body, Controller, Post } from '@nestjs/common';
import { CreateProductDto } from './dto/create-product.dto';
@Controller('products')
export class ProductsController {
@Post()
create(@Body() createProductDto: CreateProductDto) {
// createProductDto will have 'name', 'description', 'price'
console.log(createProductDto);
return 'Product created!';
}
}Why Validate Input?
Just defining a DTO isn't enough. What if a user sends invalid data?
- A
namethat's too short? - A
pricethat's negative or not a number? - Missing required fields?
Without validation, your application could:
- Store bad data.
- Crash unexpectedly.
- Be vulnerable to security exploits.
This is where NestJS Validation Pipes come in!
Introducing Validation Pipes
A Validation Pipe is a special type of middleware in NestJS that automatically validates incoming request data against your DTO definitions.
If the data doesn't match the rules you've set, the pipe will automatically throw an error, preventing invalid data from reaching your controller logic.
The Validation Duo: `class-validator` & `class-transformer`
NestJS leverages two powerful libraries for DTO validation:
class-validator: Provides decorators (like@IsString(),@IsInt()) to define validation rules directly on your DTO properties.class-transformer: Helps convert plain JavaScript objects (from the request body) into instances of your DTO classes, which is crucial forclass-validatorto work correctly.
You'll need to install them:
npm i class-validator class-transformer
Decorating Your DTOs for Validation
Let's add some validation rules to our CreateProductDto using decorators from class-validator.
These decorators ensure that the incoming data meets specific criteria, like being a string, a number, or not empty.
import { IsString, IsNumber, IsNotEmpty, IsPositive } from 'class-validator';
export class CreateProductDto {
@IsString()
@IsNotEmpty()
name: string;
@IsString()
@IsNotEmpty()
description: string;
@IsNumber()
@IsPositive()
price: number;
}Applying `ValidationPipe` to a Route
Now that our DTO has validation decorators, we need to tell NestJS to use the ValidationPipe for a specific route.
You can apply it using the @UsePipes() decorator on your controller method. This makes the pipe active only for that particular route.
import { Controller, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';
import { CreateProductDto } from './dto/create-product.dto';
@Controller('products')
export class ProductsController {
@Post()
@UsePipes(new ValidationPipe()) // Apply pipe here
create(@Body() createProductDto: CreateProductDto) {
// If validation fails, this code won't run
return `Product '${createProductDto.name}' created!`;
}
}Global Validation Pipe
Applying @UsePipes(new ValidationPipe()) to every method can be repetitive. For consistency, you can register the ValidationPipe globally in your main.ts file.
This will apply the validation pipe to all incoming requests across your entire application, simplifying your code and ensuring consistent validation.
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()); // Apply pipe globally
await app.listen(3000);
}
bootstrap();Check Your Knowledge
Time to test what you've learned about DTOs and Validation Pipes!
Recap: DTOs & Validation Pipes
You've mastered DTOs and Validation Pipes!
- DTOs are TypeScript classes that define the structure of data for your API.
- They bring clarity, consistency, and security to your data handling.
- Validation Pipes automatically enforce rules defined by
class-validatordecorators. class-transformerensures incoming data is converted to DTO instances for validation.- Pipes can be applied per-route with
@UsePipes()or globally inmain.ts.
This ensures your NestJS API always receives and processes clean, valid data.
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 20
- บทเรียน
- 76
คำถามที่พบบ่อย
บทเรียน “DTO และไปป์ตรวจสอบข้อมูล” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “DTO และไปป์ตรวจสอบข้อมูล” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 3 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “DTO และไปป์ตรวจสอบข้อมูล”
นำออบเจ็กต์ถ่ายโอนข้อมูล (DTO) มาใช้ และใช้ไปป์ตรวจสอบข้อมูลเพื่อให้แน่ใจว่าข้อมูลคำขอขาเข้าตรงตามเกณฑ์ที่กำหนด คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน
บทเรียน “DTO และไปป์ตรวจสอบข้อมูล” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม
ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- อธิบายการฉีดการพึ่งพา
- DTO และไปป์ตรวจสอบข้อมูล
- พื้นฐานการผสานรวม TypeORM