baseball-engine / backend /app /core /pagination.py
github-actions[bot]
Automated Deploy: 83f1f6fa59ef9d22788ee608e3ba12967f91dd5c
ae2c68f
Raw History Blame Contribute Delete
1.76 kB
"""Cursor pagination for lists ordered by (created_at, id)."""
import base64
import json
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from datetime import datetime
from typing import TypeVar
from uuid import UUID
from fastapi import Query
from app.core.errors import ValidationFailed
@dataclass(frozen=True)
class Cursor:
created_at: datetime
id: UUID
def encode_cursor(created_at: datetime, id_: UUID) -> str:
raw = json.dumps({"created_at": created_at.isoformat(), "id": str(id_)})
return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
def decode_cursor(value: str) -> Cursor:
try:
padded = value + "=" * (-len(value) % 4)
data = json.loads(base64.urlsafe_b64decode(padded))
return Cursor(datetime.fromisoformat(data["created_at"]), UUID(data["id"]))
except (ValueError, KeyError, TypeError) as exc:
raise ValidationFailed(fields={"cursor": "Invalid cursor."}) from exc
T = TypeVar("T")
def paginate(rows: Sequence[T], limit: int, key: Callable[[T], tuple[datetime, UUID]] | None = None
) -> tuple[list[T], str | None]:
"""Split rows fetched with limit + 1 into the page and its next cursor. key gives (created_at, id)."""
page = list(rows[:limit])
if len(rows) <= limit:
return page, None
return page, encode_cursor(*(key(page[-1]) if key else (page[-1].created_at, page[-1].id))) # type: ignore[attr-defined]
@dataclass(frozen=True)
class PageParams:
limit: int
cursor: Cursor | None
def page_params(
limit: int = Query(50, ge=1, le=200),
cursor: str | None = Query(None),
) -> PageParams:
return PageParams(limit=limit, cursor=decode_cursor(cursor) if cursor else None)