forked from mtusi2026/mtusi2026lab2
feat-(smoke test passed)
This commit is contained in:
@@ -4,6 +4,7 @@ from sqlalchemy.engine import Result
|
|||||||
from typing import List, Optional, Any, Type, TypeVar
|
from typing import List, Optional, Any, Type, TypeVar
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
import logging
|
import logging
|
||||||
|
import uuid
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
ModelType = TypeVar("ModelType")
|
ModelType = TypeVar("ModelType")
|
||||||
@@ -21,7 +22,7 @@ class DatabaseManager:
|
|||||||
result = await self.session.execute(select(self.model))
|
result = await self.session.execute(select(self.model))
|
||||||
return result.scalars().all()
|
return result.scalars().all()
|
||||||
|
|
||||||
async def get_by_id(self, record_id: int) -> Optional[ModelType]:
|
async def get_by_id(self, record_id: uuid.UUID) -> Optional[ModelType]:
|
||||||
result = await self.session.execute(select(self.model).where(self.model.id == record_id))
|
result = await self.session.execute(select(self.model).where(self.model.id == record_id))
|
||||||
return result.scalar_one_or_none()
|
return result.scalar_one_or_none()
|
||||||
|
|
||||||
@@ -58,7 +59,7 @@ class DatabaseManager:
|
|||||||
logger.error(f"Error bulk creating records in {self.model.__name__}: {e}")
|
logger.error(f"Error bulk creating records in {self.model.__name__}: {e}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
async def update_by_id(self, record_id: int, **data) -> Optional[ModelType]:
|
async def update_by_id(self, record_id: uuid.UUID, **data) -> Optional[ModelType]:
|
||||||
try:
|
try:
|
||||||
instance = await self.get_by_id(self.model, record_id)
|
instance = await self.get_by_id(self.model, record_id)
|
||||||
if instance:
|
if instance:
|
||||||
@@ -72,7 +73,7 @@ class DatabaseManager:
|
|||||||
logger.error(f"Error updating record in {self.model.__name__}: {e}")
|
logger.error(f"Error updating record in {self.model.__name__}: {e}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
async def delete_by_id(self, record_id: int) -> bool:
|
async def delete_by_id(self, record_id: uuid.UUID) -> bool:
|
||||||
try:
|
try:
|
||||||
instance = await self.get_by_id(self.model, record_id)
|
instance = await self.get_by_id(self.model, record_id)
|
||||||
if instance:
|
if instance:
|
||||||
|
|||||||
@@ -19,10 +19,14 @@ class SessionRepo(DatabaseManager):
|
|||||||
result = await super().get_by_field("token_hash", token_hash)
|
result = await super().get_by_field("token_hash", token_hash)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
async def get_by_user_id(self, user_id: str) -> Optional[Session]:
|
async def get_by_user_id(self, user_id: uuid.UUID) -> Optional[Session]:
|
||||||
result = await super().get_by_field("user_id", user_id)
|
result = await super().get_by_field("user_id", user_id)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
async def delete_by_user_id(self, token_hash: str) -> bool:
|
async def delete_by_user_id(self, user_id: uuid.UUID) -> bool:
|
||||||
result = await super().delete_by_field("token_hash", token_hash)
|
result = await super().delete_by_field("user_id", user_id)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
async def delete_by_token_hash(self, token_hash: str) -> bool:
|
||||||
|
result = await super().delete_by_field("token_hash", token_hash)
|
||||||
|
return result
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
from fastapi import HTTPException, APIRouter, Query
|
from fastapi import HTTPException, APIRouter, Query
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
import datetime
|
from datetime import datetime
|
||||||
from src.pydantic_valid.chat import CreateChat, Chat
|
from src.pydantic_valid.chat import CreateChat, Chat
|
||||||
from src.pydantic_valid.page_response import PageResponse
|
from src.pydantic_valid.page_response import PageResponse
|
||||||
from src.api.dependencies import CurrentUser, DbSession
|
from src.api.dependencies import CurrentUser, DbSession
|
||||||
@@ -64,7 +64,7 @@ async def list_chats(current_user: CurrentUser, session: DbSession, limit: int =
|
|||||||
cursor_chat_id = None
|
cursor_chat_id = None
|
||||||
if cursor:
|
if cursor:
|
||||||
created_at_str, chat_id_str = _decode_chat_cursor(cursor)
|
created_at_str, chat_id_str = _decode_chat_cursor(cursor)
|
||||||
cursor_created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00"))
|
cursor_created_at = datetime.fromisoformat(created_at_str)
|
||||||
cursor_chat_id = UUID(chat_id_str)
|
cursor_chat_id = UUID(chat_id_str)
|
||||||
|
|
||||||
chats, has_more = await repo.chats.get_user_chats_paginated(
|
chats, has_more = await repo.chats.get_user_chats_paginated(
|
||||||
@@ -78,7 +78,7 @@ async def list_chats(current_user: CurrentUser, session: DbSession, limit: int =
|
|||||||
if has_more and chats:
|
if has_more and chats:
|
||||||
last = chats[-1]
|
last = chats[-1]
|
||||||
next_cursor = _encode_chat_cursor(
|
next_cursor = _encode_chat_cursor(
|
||||||
created_at=last.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
created_at=last.created_at.fromisoformat(),
|
||||||
chat_id=str(last.id),
|
chat_id=str(last.id),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from src.pydantic_valid.page_response import PageResponse
|
|||||||
from src.api.dependencies import DbSession, CurrentUser
|
from src.api.dependencies import DbSession, CurrentUser
|
||||||
from src.api.repositories.main_repo import Repository
|
from src.api.repositories.main_repo import Repository
|
||||||
from src.utils import generate_id, get_now_iso
|
from src.utils import generate_id, get_now_iso
|
||||||
import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
@@ -74,7 +74,7 @@ async def list_messages(session: DbSession, current_user: CurrentUser, chat_id:
|
|||||||
cursor_msg_id = None
|
cursor_msg_id = None
|
||||||
if cursor:
|
if cursor:
|
||||||
created_at_str, msg_id_str = _decode_msg_cursor(str(chat_id), cursor)
|
created_at_str, msg_id_str = _decode_msg_cursor(str(chat_id), cursor)
|
||||||
cursor_created_at = datetime.fromisoformat(created_at_str.replace("Z", "+00:00"))
|
cursor_created_at = datetime.fromisoformat(created_at_str)
|
||||||
cursor_msg_id = UUID(msg_id_str)
|
cursor_msg_id = UUID(msg_id_str)
|
||||||
|
|
||||||
messages, has_more = await repo.messages.get_chat_messages(chat_id=chat_id, limit=limit, cursor_created_at=cursor_created_at, cursor_msg_id=cursor_msg_id)
|
messages, has_more = await repo.messages.get_chat_messages(chat_id=chat_id, limit=limit, cursor_created_at=cursor_created_at, cursor_msg_id=cursor_msg_id)
|
||||||
@@ -82,7 +82,7 @@ async def list_messages(session: DbSession, current_user: CurrentUser, chat_id:
|
|||||||
next_cursor = None
|
next_cursor = None
|
||||||
if has_more and messages:
|
if has_more and messages:
|
||||||
last = messages[-1]
|
last = messages[-1]
|
||||||
next_cursor = _encode_msg_cursor(chat_id=str(chat_id), created_at=last.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"), msg_id=str(last.id))
|
next_cursor = _encode_msg_cursor(chat_id=str(chat_id), created_at=last.created_at.isoformat(), msg_id=str(last.id))
|
||||||
|
|
||||||
return PageResponse(
|
return PageResponse(
|
||||||
items=[Message(id=str(msg.id), chat_id=str(msg.chat_id), sender_id=str(msg.sender_id), text=msg.text, created_at=msg.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
|
items=[Message(id=str(msg.id), chat_id=str(msg.chat_id), sender_id=str(msg.sender_id), text=msg.text, created_at=msg.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"))
|
||||||
|
|||||||
+12
-1
@@ -61,7 +61,18 @@ async def http_exception_handler(request: Request, exc: HTTPException):
|
|||||||
}
|
}
|
||||||
|
|
||||||
code = code_map.get(exc.status_code, "internal_error")
|
code = code_map.get(exc.status_code, "internal_error")
|
||||||
return create_error_response(message=str(exc.detail), code=code, status_code=exc.status_code, request_id=request_id)
|
response_headers = {"X-Request-Id": request_id}
|
||||||
|
if exc.headers:
|
||||||
|
response_headers.update(exc.headers)
|
||||||
|
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=exc.status_code,
|
||||||
|
content={"error": {
|
||||||
|
"code": code,
|
||||||
|
"message": str(exc.detail),
|
||||||
|
"request_id": request_id}
|
||||||
|
},
|
||||||
|
headers=response_headers)
|
||||||
|
|
||||||
@application.exception_handler(Exception)
|
@application.exception_handler(Exception)
|
||||||
async def global_exception_handler(request: Request, exc: Exception):
|
async def global_exception_handler(request: Request, exc: Exception):
|
||||||
|
|||||||
Reference in New Issue
Block a user