feat: port lab3 backend foundation to lab4
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session, selectinload
|
||||
|
||||
from app.db.models import Chat, ChatMember
|
||||
|
||||
|
||||
class ChatRepository:
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def get_by_id(self, chat_id: uuid.UUID) -> Chat | None:
|
||||
statement = (
|
||||
select(Chat)
|
||||
.options(selectinload(Chat.members))
|
||||
.where(Chat.id == chat_id)
|
||||
)
|
||||
|
||||
return self.db.scalar(statement)
|
||||
|
||||
def get_by_user(
|
||||
self,
|
||||
user_id: uuid.UUID,
|
||||
limit: int = 50,
|
||||
) -> list[Chat]:
|
||||
statement = (
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(ChatMember.user_id == user_id)
|
||||
.order_by(Chat.created_at.asc(), Chat.id.asc())
|
||||
.limit(limit)
|
||||
)
|
||||
|
||||
return list(self.db.scalars(statement).all())
|
||||
|
||||
def is_member(
|
||||
self,
|
||||
chat_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
) -> bool:
|
||||
statement = select(ChatMember).where(
|
||||
ChatMember.chat_id == chat_id,
|
||||
ChatMember.user_id == user_id,
|
||||
)
|
||||
|
||||
return self.db.scalar(statement) is not None
|
||||
|
||||
def create(
|
||||
self,
|
||||
title: str,
|
||||
member_ids: list[uuid.UUID],
|
||||
) -> Chat:
|
||||
chat = Chat(title=title)
|
||||
|
||||
self.db.add(chat)
|
||||
self.db.flush()
|
||||
|
||||
memberships = [
|
||||
ChatMember(
|
||||
chat_id=chat.id,
|
||||
user_id=user_id,
|
||||
)
|
||||
for user_id in member_ids
|
||||
]
|
||||
|
||||
self.db.add_all(memberships)
|
||||
self.db.flush()
|
||||
|
||||
return chat
|
||||
Reference in New Issue
Block a user