Implement DTOs to decouple repository layer from service and API layers
- Dominant language
- Python
- Stars
- 670
- Forks
- 183
- Avg merge
- 17h 7m
- Merged PRs (30d)
- 358
Description
## Motivation
- Currently, we are using ORM objects as a basic domain model. For cleaner architecture and better maintainability, it's recommended to minimize the exposure of ORM objects to higher layers (API and service layers).
## Objective
- Separation of Concerns: ORM objects often contain database-specific logic and behaviors that shouldn't leak into business logic or API concerns. By keeping them contained in the repository layer, you maintain better separation of concerns.
- Data Transfer: Instead of passing ORM objects directly, consider using Data Transfer Objects (DTOs) or domain models between layers. This gives you:
- Better control over what data is exposed
- Protection against accidentally triggering lazy loading
- Prevention of unintended database operations
- Clearer contracts between layers
- Testing Benefits: When your service layer doesn't depend directly on ORM objects, it becomes easier to unit test since you can mock simple data structures rather than complex ORM objects.
## Trade-offs
- Development Overhead: You'll need to maintain separate model classes and handle conversions between them.
- Bulk Operations: Some SQLAlchemy features for efficient bulk operations might become more complex to implement when fully abstracting away the ORM.
## Expected Sub Issue
- Implement new DTO classes using pydantic or dataclasses
- Implement mapping functions/utilities between ORM models and DTOs
- Replace `...Row` to new DTO classes in service & API layers
- Update existing unit tests
JIRA Issue: BA-622
Contributor guide
Assessment
This issue has not been assessed yet.