refactor: repository get by id mixin
This commit is contained in:
@ -1,5 +1,6 @@
|
||||
from typing import Generic, TypeVar, Type
|
||||
from typing import Generic, TypeVar, Type, Optional
|
||||
|
||||
from sqlalchemy import select, Select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
EntityType = TypeVar("EntityType")
|
||||
@ -26,8 +27,7 @@ class RepDeleteMixin(RepBaseMixin[EntityType]):
|
||||
await self.session.commit()
|
||||
|
||||
|
||||
class RepCreateMixin(Generic[EntityType, CreateType]):
|
||||
session: AsyncSession
|
||||
class RepCreateMixin(RepBaseMixin[EntityType], Generic[EntityType, CreateType]):
|
||||
entity_class: Type[EntityType]
|
||||
|
||||
async def create(self, data: CreateType) -> int:
|
||||
@ -36,3 +36,19 @@ class RepCreateMixin(Generic[EntityType, CreateType]):
|
||||
await self.session.commit()
|
||||
await self.session.refresh(obj)
|
||||
return obj.id
|
||||
|
||||
|
||||
class GetByIdMixin(RepBaseMixin[EntityType]):
|
||||
entity_class: Type[EntityType]
|
||||
|
||||
def _process_get_by_id_stmt(self, stmt: Select) -> Select:
|
||||
return stmt
|
||||
|
||||
async def get_by_id(self, item_id: int) -> 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()
|
||||
|
||||
Reference in New Issue
Block a user