refactor: entity not found exceptions handler

This commit is contained in:
2025-09-16 16:56:10 +04:00
parent 276626d6f7
commit 98d3026e0d
24 changed files with 56 additions and 49 deletions

View File

@ -7,6 +7,7 @@ from schemas.board import UpdateBoardSchema, CreateBoardSchema
class BoardRepository(RepCrudMixin[Board, CreateBoardSchema, UpdateBoardSchema]):
entity_class = Board
entity_not_found_msg = "Доска не найдена"
def _process_get_all_stmt_with_args(self, stmt: Select, *args) -> Select:
project_id = args[0]

View File

@ -15,6 +15,7 @@ class DealRepository(
RepGetByIdMixin[Deal],
):
entity_class = Deal
entity_not_found_msg = "Сделка не найдена"
async def get_all(
self,

View File

@ -5,6 +5,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repositories.base import BaseRepository
from schemas.base import BaseSchema
from utils.exceptions import ObjectNotFoundException
EntityType = TypeVar("EntityType")
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseSchema)
@ -70,18 +71,24 @@ class RepUpdateMixin(Generic[EntityType, UpdateSchemaType], RepBaseMixin[EntityT
class RepGetByIdMixin(Generic[EntityType], RepBaseMixin[EntityType]):
entity_class: Type[EntityType]
entity_not_found_msg = "Entity not found"
def _process_get_by_id_stmt(self, stmt: Select) -> Select:
return stmt
async def get_by_id(self, item_id: int) -> Optional[EntityType]:
async def get_by_id(
self, item_id: int, raise_if_not_found: Optional[bool] = True
) -> Optional[EntityType]:
stmt = select(self.entity_class).where(self.entity_class.id == item_id)
if hasattr(self, "is_deleted"):
stmt = stmt.where(self.entity_class.is_deleted.is_(False))
stmt = self._process_get_by_id_stmt(stmt)
result = await self.session.execute(stmt)
return result.scalar_one_or_none()
result = (await self.session.execute(stmt)).scalar_one_or_none()
if result is None and raise_if_not_found:
raise ObjectNotFoundException(self.entity_not_found_msg)
return result
class RepGetAllMixin(Generic[EntityType], RepBaseMixin[EntityType]):

View File

@ -10,6 +10,7 @@ class ProjectRepository(
RepCrudMixin[Project, CreateProjectSchema, UpdateProjectSchema]
):
entity_class = Project
entity_not_found_msg = "Проект не найден"
def _process_get_all_stmt(self, stmt: Select) -> Select:
return stmt.order_by(Project.id)

View File

@ -7,6 +7,7 @@ from schemas.status import UpdateStatusSchema, CreateStatusSchema
class StatusRepository(RepCrudMixin[Status, CreateStatusSchema, UpdateStatusSchema]):
entity_class = Status
entity_not_found_msg = "Статус не найден"
def _process_get_all_stmt_with_args(self, stmt: Select, *args) -> Select:
board_id = args[0]