Overview
Add behavior to objects dynamically
Decorator Pattern
13 implementations available
When to Use
- When you need to abstract data access logic
- When you want to make your code testable
- When you need to support multiple data sources
- When you want to decouple business logic from infrastructure
Available Implementations
API Response
Swagger response decorators
npx hanma add api-response --framework nest
Paginated response decoratorSuccess response wrapperCommon error responses
Message Patterns
Enhanced microservice message decorators
npx hanma add message --framework nest
Message with metadataEvent patternsVersioned messages
Roles Decorator
Role-based access control decorator
npx hanma add roles --framework nest
Role enum includedSingle role requirementMultiple roles (OR logic)
Public Route
Mark routes as public to skip auth
npx hanma add public --framework nest
Skip auth guardsWorks with global guardsSimple metadata decorator
Auth Decorator
Combined authentication decorator
npx hanma add auth --framework nest
JWT + Roles combinedSwagger integrationAdminOnly shortcut
Roles Guard
Role-based access control
npx hanma add roles-guard --framework nest
OR logic (any role)AND logic (all roles)Custom error messages
Basic Example
// Decorator Pattern implementation example
// This shows the basic structure of decorator pattern in NestJS
// Define your interface
interface IRepository {
findAll(): Promise<T[]>;
findById(id: string): Promise<T | null>;
create(data: CreateDto): Promise<T>;
update(id: string, data: UpdateDto): Promise<T>;
delete(id: string): Promise<void>;
}
// Implement the pattern
class DecoratorRepository implements IRepository {
async findAll(): Promise<T[]> {
// Implementation
}
async findById(id: string): Promise<T | null> {
// Implementation
}
async create(data: CreateDto): Promise<T> {
// Implementation
}
async update(id: string, data: UpdateDto): Promise<T> {
// Implementation
}
async delete(id: string): Promise<void> {
// Implementation
}
}
// Use the pattern
const repository = new DecoratorRepository();
const items = await repository.findAll();
Frequently Asked Questions
What is Decorator Pattern?
Add behavior to objects dynamically. It's a well-established software design pattern that helps organize code for better maintainability and testability.
How does Decorator Pattern work with NestJS?
NestJS provides excellent support for this pattern through its dependency injection system and middleware composition.
What are the benefits?
Improved testability, separation of concerns, easier maintenance, and flexibility to change implementations without affecting business logic.
When should I avoid this pattern?
For very simple applications with minimal logic, the pattern may add unnecessary complexity. Use judgment based on project requirements.