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, schemars::JsonSchema)]
71#[schemars(rename = "Paginated_{T}", extend("x-capy-pagination" = true))]
72pub struct Page<T> {
73    /// Public response objects for the requested page.
74    pub data: Vec<T>,
75    /// Pagination totals and the requested page.
76    pub meta: PageMeta,
77}
78
79/// Conventional pagination metadata. Empty collections have one empty page.
80#[derive(Debug, Serialize, schemars::JsonSchema)]
81#[schemars(rename = "PaginationMeta")]
82pub struct PageMeta {
83    /// Requested one-based page.
84    pub page: u64,
85    /// Requested maximum items per page.
86    pub per_page: u64,
87    /// Total items counted by the application's query.
88    pub total: u64,
89    /// Last populated page, or one for an empty collection.
90    pub last_page: u64,
91}
92
93/// JSON contract name for the existing bounded collection response.
94pub type Paginated<T> = Page<T>;
95
96/// JSON contract name for the existing pagination metadata.
97pub type PaginationMeta = PageMeta;
98
99impl schemars::JsonSchema for Pagination {
100    fn schema_name() -> std::borrow::Cow<'static, str> {
101        "Pagination".into()
102    }
103
104    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
105        // These are URL query values; optional fields are absent rather than JSON null.
106        schemars::json_schema!({
107            "type": "object",
108            "properties": {
109                "page": {"type": "integer", "minimum": 1, "default": 1},
110                "per_page": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20}
111            }
112        })
113    }
114}
115
116impl<T> Page<T> {
117    /// Wrap already-bounded query results. Count and fetch may observe concurrent writes;
118    /// use an appropriate database transaction when a consistent snapshot is needed.
119    pub fn new(data: Vec<T>, pagination: Pagination, total: u64) -> Self {
120        Self {
121            data,
122            meta: PageMeta {
123                page: pagination.page,
124                per_page: pagination.per_page,
125                total,
126                last_page: total.div_ceil(pagination.per_page).max(1),
127            },
128        }
129    }
130}