refactor: update repository mixin
This commit is contained in:
@ -5,6 +5,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
EntityType = TypeVar("EntityType")
|
||||
CreateType = TypeVar("CreateType")
|
||||
UpdateType = TypeVar("UpdateType")
|
||||
|
||||
|
||||
class RepBaseMixin(Generic[EntityType]):
|
||||
@ -38,6 +39,29 @@ class RepCreateMixin(RepBaseMixin[EntityType], Generic[EntityType, CreateType]):
|
||||
return obj.id
|
||||
|
||||
|
||||
class RepUpdateMixin(RepBaseMixin[EntityType], Generic[EntityType, UpdateType]):
|
||||
async def _apply_update_data_to_model(
|
||||
self,
|
||||
model: EntityType,
|
||||
data: UpdateType,
|
||||
with_commit: Optional[bool] = False,
|
||||
fields: Optional[list[str]] = None,
|
||||
) -> EntityType:
|
||||
if fields is None:
|
||||
fields = data.model_dump().keys()
|
||||
|
||||
for field in fields:
|
||||
value = getattr(data, field)
|
||||
if value is not None:
|
||||
setattr(model, field, value)
|
||||
|
||||
if with_commit:
|
||||
self.session.add(model)
|
||||
await self.session.commit()
|
||||
await self.session.refresh(model)
|
||||
return model
|
||||
|
||||
|
||||
class GetByIdMixin(RepBaseMixin[EntityType]):
|
||||
entity_class: Type[EntityType]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user