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
+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}