File size: 1,755 Bytes
2756f0f
 
 
 
ae2c68f
2756f0f
 
ae2c68f
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2c68f
 
 
 
 
 
 
 
 
 
 
 
2756f0f
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""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)