refactor: entity not found exceptions handler
This commit is contained in:
@ -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]):
|
||||
|
||||
Reference in New Issue
Block a user