Pipes trong NestJS

Pipes là một công cụ mạnh mẽ để validatetransform data. Một pipe là một class được trang trí bằng @Injectable() decorator, implement interface PipeTransform. Pipes được thực thi trước khi data tới controller methods.

Khái Niệm Pipe

Pipe có hai use cases chính:
  1. Transformation - Transform input data thành một dạng mong muốn (e.g., string → number)
  2. Validation - Validate input data và throw exception nếu invalid

Built-in Pipes

NestJS cung cấp sẵn các pipes hữu ích:

Custom Pipes

1. Validation Pipe

2. Transformation Pipe

3. Parse Int Pipe (Custom)

4. Validation Pipe với Default Value

Validation with class-validator

Setup

DTOs with Decorators

Global Validation Pipe

Sử dụng với Controllers

Pipes at Different Scopes

Method-level

Global-level

Module-level (Provider)

Ví Dụ Thực Tế

1. Custom Validation Pipe

2. Parse Comma-Separated List Pipe

3. Parse JSON Pipe

4. Sanitize HTML Pipe

5. Trim String Pipe

6. Lowercase Pipe

7. Custom Enum Validation Pipe

8. File Upload Validation Pipe

9. Date Parsing Pipe

Validation Decorators

Built-in Decorators

Best Practices

1. Reusable DTOs

2. Nested Validation

3. Conditional Validation

4. Custom Validation Decorators

5. Validation Groups

Complete Example

Kết Luận

Pipes là công cụ quan trọng để:
  • Validate input data trước khi tới logic xử lý
  • Transform data thành dạng mong muốn
  • Đảm bảo type safety
  • Tạo consistent error responses
  • Giảm boilerplate code trong controllers
Sử dụng pipes đúng cách giúp bạn:
  • Xây dựng ứng dụng robust và secure
  • Validate data một cách centralized
  • Cải thiện code quality
  • Giảm bugs liên quan đến invalid data