Skip to main content

capy_http/
pagination.rs

1use capy_core::AppError;
2use serde::{Deserialize, Serialize};
3
4/// Validated, one-based page parameters. Use `Query<Pagination>` in a handler.
5/// Defaults to page 1 and 20 items; page size must be 1..=100.
6#[derive(Clone, Copy, Debug, Deserialize)]
7#[serde(try_from = "Parameters")]
8pub struct Pagination {
9    page: u64,
10    per_page: u64,
11}
12
13#[derive(Default, Deserialize)]
14#[serde(default)]
15struct Parameters {
16    page: Option<u64>,
17    per_page: Option<u64>,
18}
19
20impl TryFrom<Parameters> for Pagination {
21    type Error = AppError;
22    fn try_from(value: Parameters) -> Result<Self, Self::Error> {
23        Self::new(value.page.unwrap_or(1), value.per_page.unwrap_or(20))
24    }
25}
26
27impl Default for Pagination {
28    fn default() -> Self {
29        Self {
30            page: 1,
31            per_page: 20,
32        }
33    }
34}
35
36impl Pagination {
37    /// Validate page and size, including the database offset's integer range.
38    pub fn new(page: u64, per_page: u64) -> Result<Self, AppError> {
39        if page == 0 || !(1..=100).contains(&per_page) {
40            return Err(AppError::BadRequest(
41                "page must be at least 1 and per_page must be 1..=100".into(),
42            ));
43        }
44        if (page - 1)
45            .checked_mul(per_page)
46            .is_none_or(|offset| offset > i64::MAX as u64)
47        {
48            return Err(AppError::BadRequest(
49                "Pagination offset is too large".into(),
50            ));
51        }
52        Ok(Self { page, per_page })
53    }
54
55    /// Requested page, starting at one.
56    pub fn page(self) -> u64 {
57        self.page
58    }
59    /// Validated page size, suitable for SeaORM's `paginate`.
60    pub fn per_page(self) -> u64 {
61        self.per_page
62    }
63    /// Validated zero-based SQL offset for adapters without a paginator.
64    pub fn offset(self) -> u64 {
65        (self.page - 1) * self.per_page
66    }
67}
68
69/// A bounded collection response. The caller supplies a paginated query's rows.
70#[derive(Debug, Serialize)]
71pub struct Page<T> {
72    /// Public response objects for the requested page.
73    pub data: Vec<T>,
74    /// Pagination totals and the requested page.
75    pub meta: PageMeta,
76}
77
78/// Conventional pagination metadata. Empty collections have one empty page.
79#[derive(Debug, Serialize)]
80pub struct PageMeta {
81    /// Requested one-based page.
82    pub page: u64,
83    /// Requested maximum items per page.
84    pub per_page: u64,
85    /// Total items counted by the application's query.
86    pub total: u64,
87    /// Last populated page, or one for an empty collection.
88    pub last_page: u64,
89}
90
91impl<T> Page<T> {
92    /// Wrap already-bounded query results. Count and fetch may observe concurrent writes;
93    /// use an appropriate database transaction when a consistent snapshot is needed.
94    pub fn new(data: Vec<T>, pagination: Pagination, total: u64) -> Self {
95        Self {
96            data,
97            meta: PageMeta {
98                page: pagination.page,
99                per_page: pagination.per_page,
100                total,
101                last_page: total.div_ceil(pagination.per_page).max(1),
102            },
103        }
104    }
105}