use serde::{Deserialize, Serialize};
pub const MAX_PER_PAGE: u64 = 100;
pub const DEFAULT_PER_PAGE: u64 = 20;
pub const DEFAULT_CURSOR_LIMIT: u64 = 50;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub struct PageParams {
pub page: u64,
pub per_page: u64,
}
impl Default for PageParams {
fn default() -> Self {
Self {
page: 1,
per_page: DEFAULT_PER_PAGE,
}
}
}
impl PageParams {
pub fn new(page: u64, per_page: u64) -> Self {
Self {
page: page.max(1),
per_page: per_page.clamp(1, MAX_PER_PAGE),
}
}
pub fn offset(self) -> u64 {
(self.page.saturating_sub(1)).saturating_mul(self.per_page)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PageMeta {
pub page: u64,
pub per_page: u64,
pub total: u64,
pub last_page: u64,
pub has_more: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PageResult<T> {
pub items: Vec<T>,
pub meta: PageMeta,
}
impl<T: Serialize> PageResult<T> {
pub fn new(items: Vec<T>, total: u64, params: PageParams) -> Self {
let clamped = PageParams::new(params.page, params.per_page);
let last_page = if total == 0 {
1
} else {
total.div_ceil(clamped.per_page)
};
let has_more = clamped.page < last_page;
Self {
items,
meta: PageMeta {
page: clamped.page,
per_page: clamped.per_page,
total,
last_page,
has_more,
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub struct CursorParams {
pub before: Option<i64>,
pub after: Option<i64>,
pub limit: u64,
}
impl Default for CursorParams {
fn default() -> Self {
Self {
before: None,
after: None,
limit: DEFAULT_CURSOR_LIMIT,
}
}
}
impl CursorParams {
pub fn new(before: Option<i64>, after: Option<i64>, limit: u64) -> Self {
Self {
before,
after,
limit: limit.clamp(1, MAX_PER_PAGE),
}
}
}