Delegate invite persistence to InviteRepository

- Add create(), update(), and reload_with_relationships() methods to InviteRepository
- Update InviteService to use repository methods instead of direct db operations
This commit is contained in:
counterweight 2025-12-25 18:52:52 +01:00
parent 04333d210b
commit c4594a3f73
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C
2 changed files with 49 additions and 16 deletions

View file

@ -80,3 +80,49 @@ class InviteRepository:
query = query.order_by(desc(Invite.created_at)).offset(offset).limit(per_page)
result = await self.db.execute(query)
return list(result.scalars().all())
async def create(self, invite: Invite) -> Invite:
"""
Create a new invite record.
Args:
invite: Invite instance to persist
Returns:
Created Invite record (committed and refreshed)
"""
self.db.add(invite)
await self.db.commit()
await self.db.refresh(invite)
return invite
async def update(self, invite: Invite) -> Invite:
"""
Update an existing invite record.
Args:
invite: Invite instance to update
Returns:
Updated Invite record (committed and refreshed)
"""
await self.db.commit()
await self.db.refresh(invite)
return invite
async def reload_with_relationships(self, invite_id: int) -> Invite:
"""
Reload an invite with all relationships eagerly loaded.
Args:
invite_id: ID of the invite to reload
Returns:
Invite record with relationships loaded
"""
result = await self.db.execute(
select(Invite)
.options(joinedload(Invite.godfather), joinedload(Invite.used_by))
.where(Invite.id == invite_id)
)
return result.scalar_one()

View file

@ -147,20 +147,10 @@ class InviteService:
godfather_id=godfather_id,
status=InviteStatus.READY,
)
self.db.add(invite)
try:
await self.db.commit()
await self.db.refresh(invite)
invite = await self.invite_repo.create(invite)
# Reload with relationships
from sqlalchemy import select
from sqlalchemy.orm import joinedload
result = await self.db.execute(
select(Invite)
.options(joinedload(Invite.godfather), joinedload(Invite.used_by))
.where(Invite.id == invite.id)
)
invite = result.scalar_one()
invite = await self.invite_repo.reload_with_relationships(invite.id)
break
except IntegrityError:
await self.db.rollback()
@ -200,7 +190,4 @@ class InviteService:
invite.status = InviteStatus.REVOKED
invite.revoked_at = datetime.now(UTC)
await self.db.commit()
await self.db.refresh(invite)
return invite
return await self.invite_repo.update(invite)