|
| 1 | +"""Pagination models and utilities.""" |
| 2 | + |
| 3 | +from typing import Generic, TypeVar |
| 4 | + |
| 5 | +from pydantic import BaseModel, Field |
| 6 | + |
| 7 | +T = TypeVar("T") |
| 8 | + |
| 9 | + |
| 10 | +class PaginationParams(BaseModel): |
| 11 | + """Query parameters for pagination.""" |
| 12 | + |
| 13 | + page: int = Field(default=1, ge=1, description="Page number (1-indexed)") |
| 14 | + limit: int = Field(default=20, ge=1, le=100, description="Items per page") |
| 15 | + |
| 16 | + @property |
| 17 | + def offset(self) -> int: |
| 18 | + """Calculate offset for database query.""" |
| 19 | + return (self.page - 1) * self.limit |
| 20 | + |
| 21 | + |
| 22 | +class PaginationMeta(BaseModel): |
| 23 | + """Pagination metadata.""" |
| 24 | + |
| 25 | + page: int = Field(description="Current page number") |
| 26 | + limit: int = Field(description="Items per page") |
| 27 | + total: int = Field(description="Total number of items") |
| 28 | + total_pages: int = Field(description="Total number of pages") |
| 29 | + has_next: bool = Field(description="Whether there is a next page") |
| 30 | + has_prev: bool = Field(description="Whether there is a previous page") |
| 31 | + |
| 32 | + |
| 33 | +class PaginatedResponse(BaseModel, Generic[T]): |
| 34 | + """Generic paginated response wrapper.""" |
| 35 | + |
| 36 | + data: list[T] |
| 37 | + meta: PaginationMeta |
| 38 | + |
| 39 | + @classmethod |
| 40 | + def create( |
| 41 | + cls, |
| 42 | + data: list[T], |
| 43 | + total: int, |
| 44 | + page: int, |
| 45 | + limit: int, |
| 46 | + ) -> "PaginatedResponse[T]": |
| 47 | + """ |
| 48 | + Create a paginated response. |
| 49 | +
|
| 50 | + Args: |
| 51 | + data: List of items for the current page |
| 52 | + total: Total number of items across all pages |
| 53 | + page: Current page number (1-indexed) |
| 54 | + limit: Items per page |
| 55 | +
|
| 56 | + Returns: |
| 57 | + PaginatedResponse with data and metadata |
| 58 | + """ |
| 59 | + total_pages = (total + limit - 1) // limit if total > 0 else 0 |
| 60 | + |
| 61 | + return cls( |
| 62 | + data=data, |
| 63 | + meta=PaginationMeta( |
| 64 | + page=page, |
| 65 | + limit=limit, |
| 66 | + total=total, |
| 67 | + total_pages=total_pages, |
| 68 | + has_next=page < total_pages, |
| 69 | + has_prev=page > 1, |
| 70 | + ), |
| 71 | + ) |
0 commit comments