Repository Interfaces
Repository interfaces define contracts for data persistence operations. They belong to the domain layer but are implemented in the infrastructure layer, following the Dependency Inversion Principle.Overview
Repositories provide an abstraction over data access, allowing the domain layer to remain independent of specific persistence technologies (e.g., MongoDB, PostgreSQL).Architecture Pattern
Architecture Pattern
The repository pattern follows these principles:
- Interface in Domain Layer: Defines what operations are needed
- Implementation in Infrastructure Layer: Provides concrete implementation
- Dependency Injection: Use cases depend on interfaces, not implementations
ICustomerRepository
Interface for managing customer data persistence.Interface Definition
src/domain/repositories/ICustomerRepository.ts
Methods
create
create
Customer entity to persist (without
id field)Promise<Customer> - The created customer with generated idExample:findByEmail
findByEmail
Email address to search for
Promise<Customer | null> - The customer if found, null otherwiseExample:findById
findById
Customer ID to search for
Promise<Customer | null> - The customer if found, null otherwiseExample:Implementation Reference
The MongoDB implementation can be found at:src/infrastructure/persistence/mongodb/MongoCustomerRepository.ts
IOrderRepository
Interface for managing order data persistence.Interface Definition
src/domain/repositories/IOrderRepository.ts
Methods
create
create
Order entity to persist (without
id field)Promise<Order> - The created order with generated idExample:findByCustomerId
findByCustomerId
Customer ID to search for
Promise<Order[]> - Array of orders (empty array if none found)Example:findByReceiptId
findByReceiptId
Payment gateway receipt/transaction ID
Promise<Order | null> - The order if found, null otherwiseExample:Implementation Reference
The MongoDB implementation can be found at:src/infrastructure/persistence/mongodb/MongoOrderRepository.ts
Repository Design Patterns
Dependency Injection
Dependency Injection
Repositories are injected into use cases via constructor injection:This allows:
- Testing with mock repositories
- Switching implementations without changing use cases
- Following SOLID principles
Error Handling
Error Handling
Repository methods should throw errors for exceptional cases:Use cases should handle repository errors:
Testing
Testing
Mock repositories for unit testing use cases:
Return Types
Return Types
Repository methods follow these conventions:
- Create operations: Return the created entity with generated
id - Find single: Return
Entity | null(null if not found) - Find multiple: Return
Entity[](empty array if none found) - Update/Delete: Return
voidorbooleanindicating success
