Overview
Maintain a list of objects and coordinate writing
Unit of Work
3 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
Prisma Service
Prisma client as injectable NestJS service
npx hanma add prisma-service --framework nest
Module lifecycle integrationHealth check methodTransaction helper with retry
Drizzle Service
Drizzle ORM service with PostgreSQL
npx hanma add drizzle-service --framework nest
PostgreSQL connection poolTransaction helperRaw SQL execution
Kafka Service
Apache Kafka client for event-driven architecture
npx hanma add kafka-service --framework nest
Producer with compressionConsumer subscriptionsTopic management
Basic Example
// Unit of Work implementation example
// This shows the basic structure of unit of work 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 UnitRepository 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 UnitRepository();
const items = await repository.findAll();
Frequently Asked Questions
What is Unit of Work?
Maintain a list of objects and coordinate writing. It's a well-established software design pattern that helps organize code for better maintainability and testability.
How does Unit of Work 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.