Custom Decorators trong NestJS

Decorators là một tính năng mạnh mẽ của TypeScript cho phép bạn thêm annotations và modify classes, methods, properties, và parameters. NestJS cung cấp một set decorators built-in, nhưng bạn cũng có thể tạo custom decorators cho nhu cầu cụ thể.

Khái Niệm Decorator

Decorator là một function trả về một function khác. Nó được sử dụng để modify hoặc enhance behavior của classes, methods, properties, hoặc parameters.

Reflection và Metadata

NestJS sử dụng reflect-metadata library để làm việc với decorators:
Đảm bảo import ở top của main.ts:

Method Decorators

1. Simple Method Decorator

2. Timer Decorator

3. Validate Decorator

4. Authorize Decorator

Parameter Decorators

1. Custom Param Decorator

2. User Decorator

3. Paginate Decorator

4. Headers Decorator

5. Query Decorator

6. IP Decorator

Class Decorators

1. Controller with Prefix

2. Serializable Decorator

Property Decorators

1. Required Decorator

2. Validate Min/Max

Combining Multiple Decorators

Ví Dụ Custom Decorators Thực Tế

1. Timeout Decorator

2. Deprecated Decorator

3. Cache Decorator

4. ValidateEmail Decorator

5. RateLimit Decorator

6. Log Decorator

7. Transform Decorator

Metadata with Reflector

Best Practices

1. Tạo Reusable Decorators

2. Document Custom Decorators

3. Use applyDecorators for Compound Decorators

4. Proper Error Handling in Parameter Decorators

5. Type-Safe Decorators

Complete Example

Kết Luận

Custom Decorators là công cụ mạnh mẽ để:
  • Reduce boilerplate code - Tránh lặp lại code
  • Enhance readability - Code dễ đọc hơn
  • Centralize logic - Tập trung logic ở một nơi
  • Reuse functionality - Tái sử dụng across routes
  • Add metadata - Gắn metadata vào classes/methods
Sử dụng Custom Decorators đúng cách giúp bạn:
  • Tạo elegant và maintainable code
  • Tái sử dụng authentication/authorization logic
  • Giảm code duplication
  • Cải thiện code organization
  • Tạo semantic API cho ứng dụng