Overview
Chain processing objects to handle requests
Middleware Pattern
6 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
HTTP Exception Filter
Global HTTP exception handling
npx hanma add http-exception-filter --framework nest
Structured error responseRequest ID includedStatus-based logging
All Exceptions Filter
Catch-all exception filter
npx hanma add all-exceptions-filter --framework nest
Catches all errorsSensitive data sanitizationProduction-safe messages
Validation Filter
Validation exception handling
npx hanma add validation-filter --framework nest
Field-level errorsCustom ValidationExceptionHelper functions
Prisma Exception Filter
Prisma database error handling
npx hanma add prisma-exception-filter --framework nest
Unique constraint errorsNot found errorsForeign key errors
Request ID Middleware
Request ID generation for tracing
npx hanma add request-id-middleware --framework nest
UUID generationCorrelation ID supportResponse headers
Logger Middleware
HTTP request logging
npx hanma add logger-middleware --framework nest
Request/response loggingSensitive data maskingConfigurable options
Basic Example
// Middleware Pattern implementation example
// This shows the basic structure of middleware 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 MiddlewareRepository 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 MiddlewareRepository();
const items = await repository.findAll();
Frequently Asked Questions
What is Middleware Pattern?
Chain processing objects to handle requests. It's a well-established software design pattern that helps organize code for better maintainability and testability.
How does Middleware 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.