capy-http 0.10.0

Axum routing and JSON response conveniences for Capy.
Documentation
use capy_core::AppError;
use serde::{Deserialize, Serialize};

/// Validated, one-based page parameters. Use `Query<Pagination>` in a handler.
/// Defaults to page 1 and 20 items; page size must be 1..=100.
#[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 {
    /// Validate page and size, including the database offset's integer range.
    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 })
    }

    /// Requested page, starting at one.
    pub fn page(self) -> u64 {
        self.page
    }
    /// Validated page size, suitable for SeaORM's `paginate`.
    pub fn per_page(self) -> u64 {
        self.per_page
    }
    /// Validated zero-based SQL offset for adapters without a paginator.
    pub fn offset(self) -> u64 {
        (self.page - 1) * self.per_page
    }
}

/// A bounded collection response. The caller supplies a paginated query's rows.
#[derive(Debug, Serialize, schemars::JsonSchema)]
#[schemars(rename = "Paginated_{T}", extend("x-capy-pagination" = true))]
pub struct Page<T> {
    /// Public response objects for the requested page.
    pub data: Vec<T>,
    /// Pagination totals and the requested page.
    pub meta: PageMeta,
}

/// Conventional pagination metadata. Empty collections have one empty page.
#[derive(Debug, Serialize, schemars::JsonSchema)]
#[schemars(rename = "PaginationMeta")]
pub struct PageMeta {
    /// Requested one-based page.
    pub page: u64,
    /// Requested maximum items per page.
    pub per_page: u64,
    /// Total items counted by the application's query.
    pub total: u64,
    /// Last populated page, or one for an empty collection.
    pub last_page: u64,
}

/// JSON contract name for the existing bounded collection response.
pub type Paginated<T> = Page<T>;

/// JSON contract name for the existing pagination metadata.
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 {
        // These are URL query values; optional fields are absent rather than JSON null.
        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> {
    /// Wrap already-bounded query results. Count and fetch may observe concurrent writes;
    /// use an appropriate database transaction when a consistent snapshot is needed.
    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),
            },
        }
    }
}