38 lines
1.3 KiB
Python
38 lines
1.3 KiB
Python
"""User repository"""
|
|
from typing import Optional
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy.orm import selectinload
|
|
|
|
from app.repositories.base import BaseRepository
|
|
from app.db.models import User
|
|
|
|
|
|
class UserRepository(BaseRepository[User]):
|
|
"""User repository with custom methods"""
|
|
|
|
def __init__(self, session: AsyncSession):
|
|
super().__init__(User, session)
|
|
|
|
async def get_by_did(self, did: str) -> Optional[User]:
|
|
"""Get user by DID"""
|
|
result = await self.session.execute(
|
|
select(User).where(User.did == did)
|
|
)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_or_create(self, did: str, handle: Optional[str] = None) -> User:
|
|
"""Get existing user or create new one"""
|
|
user = await self.get_by_did(did)
|
|
if not user:
|
|
user = await self.create(did=did, handle=handle)
|
|
return user
|
|
|
|
async def get_with_cards(self, user_id: int) -> Optional[User]:
|
|
"""Get user with all their cards"""
|
|
result = await self.session.execute(
|
|
select(User)
|
|
.options(selectinload(User.cards))
|
|
.where(User.id == user_id)
|
|
)
|
|
return result.scalar_one_or_none() |