use capy_core::AppError;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(try_from = "Parameters")]
pub struct Pagination {
page: u64,
per_page: u64,
}
#[derive(Default, Deserialize)]
#[serde(default)]
struct Parameters {
page: Option<u64>,
per_page: Option<u64>,
}
impl TryFrom<Parameters> for Pagination {
type Error = AppError;
fn try_from(value: Parameters) -> Result<Self, Self::Error> {
Self::new(value.page.unwrap_or(1), value.per_page.unwrap_or(20))
}
}
impl Default for Pagination {
fn default() -> Self {
Self {
page: 1,
per_page: 20,
}
}
}
impl Pagination {
pub fn new(page: u64, per_page: u64) -> Result<Self, AppError> {
if page == 0 || !(1..=100).contains(&per_page) {
return Err(AppError::BadRequest(
"page must be at least 1 and per_page must be 1..=100".into(),
));
}
if (page - 1)
.checked_mul(per_page)
.is_none_or(|offset| offset > i64::MAX as u64)
{
return Err(AppError::BadRequest(
"Pagination offset is too large".into(),
));
}
Ok(Self { page, per_page })
}
pub fn page(self) -> u64 {
self.page
}
pub fn per_page(self) -> u64 {
self.per_page
}
pub fn offset(self) -> u64 {
(self.page - 1) * self.per_page
}
}
#[derive(Debug, Serialize, schemars::JsonSchema)]
#[schemars(rename = "Paginated_{T}", extend("x-capy-pagination" = true))]
pub struct Page<T> {
pub data: Vec<T>,
pub meta: PageMeta,
}
#[derive(Debug, Serialize, schemars::JsonSchema)]
#[schemars(rename = "PaginationMeta")]
pub struct PageMeta {
pub page: u64,
pub per_page: u64,
pub total: u64,
pub last_page: u64,
}
pub type Paginated<T> = Page<T>;
pub type PaginationMeta = PageMeta;
impl schemars::JsonSchema for Pagination {
fn schema_name() -> std::borrow::Cow<'static, str> {
"Pagination".into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "object",
"properties": {
"page": {"type": "integer", "minimum": 1, "default": 1},
"per_page": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20}
}
})
}
}
impl<T> Page<T> {
pub fn new(data: Vec<T>, pagination: Pagination, total: u64) -> Self {
Self {
data,
meta: PageMeta {
page: pagination.page,
per_page: pagination.per_page,
total,
last_page: total.div_ceil(pagination.per_page).max(1),
},
}
}
}