feat: persist messenger data in PostgreSQL

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-01 22:05:22 +03:00
parent f72725c36a
commit 07a06f186c
10 changed files with 602 additions and 0 deletions
+71
View File
@@ -0,0 +1,71 @@
"""Lab 1 HTTP routes."""
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query
from .models import CreateChat, CreateMessage, CreateUser
from .store import store
router = APIRouter()
@router.get("/health/live")
def live():
return {"status": "ok"}
@router.get("/health/ready")
def ready():
return store.ready()
@router.post("/api/v1/users", status_code=201)
def register_user(body: CreateUser):
return store.register(body.username, body.display_name, body.password)
def current_user() -> dict:
# U2 replaces this placeholder with PostgreSQL-backed Bearer sessions.
raise HTTPException(401, headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
@router.get("/api/v1/users/me")
def user_me(actor: dict = Depends(current_user)):
return actor
@router.post("/api/v1/chats", status_code=201)
def create_chat(body: CreateChat, actor: dict = Depends(current_user)):
return store.create_chat(actor["id"], body.title, body.member_ids)
@router.get("/api/v1/chats")
def list_chats(
limit: str = Query("50"), cursor: str | None = Query(None, min_length=1), actor: dict = Depends(current_user)
):
if not limit.isdecimal() or not 1 <= int(limit) <= 100:
raise HTTPException(400)
return store.list_chats(actor["id"], int(limit), cursor)
@router.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: UUID, actor: dict = Depends(current_user)):
return store.chat(actor["id"], str(chat_id))
@router.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def create_message(chat_id: UUID, body: CreateMessage, actor: dict = Depends(current_user)):
return store.create_message(actor["id"], str(chat_id), body.text)
@router.get("/api/v1/chats/{chat_id}/messages")
def list_messages(
chat_id: UUID,
limit: str = Query("50"),
cursor: str | None = Query(None, min_length=1),
actor: dict = Depends(current_user),
):
if not limit.isdecimal() or not 1 <= int(limit) <= 100:
raise HTTPException(400)
return store.list_messages(actor["id"], str(chat_id), int(limit), cursor)