refactor: share pagination validation and sort keys

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-01 22:32:17 +03:00
parent 82b2fbe850
commit fbd5ec32f5
2 changed files with 13 additions and 11 deletions
+8 -6
View File
@@ -29,6 +29,12 @@ def current_user(x_user_id: str | None = Header(None, alias="X-User-Id")) -> dic
return store.user(x_user_id)
def parse_limit(value: str) -> int:
if not value.isdecimal() or not 1 <= int(value) <= 100:
raise HTTPException(400)
return int(value)
@router.get("/api/v1/users/me")
def user_me(actor: dict = Depends(current_user)):
return actor
@@ -43,9 +49,7 @@ def create_chat(body: CreateChat, actor: dict = Depends(current_user)):
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)
return store.list_chats(actor["id"], parse_limit(limit), cursor)
@router.get("/api/v1/chats/{chat_id}")
@@ -65,6 +69,4 @@ def list_messages(
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)
return store.list_messages(actor["id"], str(chat_id), parse_limit(limit), cursor)
+5 -5
View File
@@ -15,7 +15,7 @@ def now() -> str:
return datetime.now(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def message_key(item: dict) -> tuple[str, str]:
def item_key(item: dict) -> tuple[str, str]:
return item["created_at"], item["id"]
@@ -88,10 +88,10 @@ class Store:
with self.lock:
items = sorted(
(chat for chat in self.chats.values() if actor_id in chat["member_ids"]),
key=lambda chat: (chat["created_at"], chat["id"]),
key=item_key,
)
if after is not None:
items = [chat for chat in items if (chat["created_at"], chat["id"]) > after]
items = [chat for chat in items if item_key(chat) > after]
page = items[:limit]
next_cursor = encode_cursor(f"chats:{actor_id}", page[-1]) if len(items) > limit else None
return {"items": page, "next_cursor": next_cursor}
@@ -105,7 +105,7 @@ class Store:
"id": str(uuid4()), "chat_id": chat_id, "sender_id": actor_id,
"text": text, "created_at": now(),
}
insort(self.messages[chat_id], message, key=message_key)
insort(self.messages[chat_id], message, key=item_key)
return message
def list_messages(self, actor_id: str, chat_id: str, limit: int, cursor: str | None) -> dict:
@@ -115,7 +115,7 @@ class Store:
raise HTTPException(404)
after = decode_cursor(cursor, f"messages:{chat_id}")
items = self.messages[chat_id]
start = bisect_right(items, after, key=message_key) if after is not None else 0
start = bisect_right(items, after, key=item_key) if after is not None else 0
page = items[start:start + limit]
next_cursor = encode_cursor(f"messages:{chat_id}", page[-1]) if len(items) > start + limit else None
return {"items": page, "next_cursor": next_cursor}