1use capy_core::AppError;
2use serde::{Deserialize, Serialize};
3
4#[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 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 pub fn page(self) -> u64 {
57 self.page
58 }
59 pub fn per_page(self) -> u64 {
61 self.per_page
62 }
63 pub fn offset(self) -> u64 {
65 (self.page - 1) * self.per_page
66 }
67}
68
69#[derive(Debug, Serialize, schemars::JsonSchema)]
71#[schemars(rename = "Paginated_{T}", extend("x-capy-pagination" = true))]
72pub struct Page<T> {
73 pub data: Vec<T>,
75 pub meta: PageMeta,
77}
78
79#[derive(Debug, Serialize, schemars::JsonSchema)]
81#[schemars(rename = "PaginationMeta")]
82pub struct PageMeta {
83 pub page: u64,
85 pub per_page: u64,
87 pub total: u64,
89 pub last_page: u64,
91}
92
93pub type Paginated<T> = Page<T>;
95
96pub 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 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 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}