use serde::{Deserialize, Serialize};
use smart_default::SmartDefault;
use std::collections::HashMap;
#[cfg(feature = "openapi")]
use utoipa::{IntoParams, ToSchema};
#[derive(Debug, Clone, SmartDefault, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema, IntoParams))]
#[serde(default)]
pub struct PaginatedQuery {
#[default = 1]
pub page: u64,
#[default = 10]
pub page_size: u64,
pub sort_by: Option<String>,
#[default(_code = "SortOrder::Desc")]
pub sort_order: SortOrder,
pub search: Option<String>,
pub filters: Option<HashMap<String, String>>,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub enum SortOrder {
#[default]
Desc,
Asc,
}
impl PaginatedQuery {
pub fn skip(&self) -> u64 {
(self.page - 1) * self.page_size
}
pub fn limit(&self) -> i64 {
self.page_size as i64
}
}
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(bound = "T: ToSchema"))]
pub struct PaginatedData<T> {
pub items: Vec<T>,
pub total_count: u64,
pub page: u64,
pub page_size: u64,
pub total_pages: u64,
}
impl<T> PaginatedData<T> {
pub fn map<P, F>(self, f: F) -> PaginatedData<P>
where
F: FnMut(T) -> P,
{
PaginatedData {
items: self.items.into_iter().map(f).collect(),
total_count: self.total_count,
page: self.page,
page_size: self.page_size,
total_pages: self.total_pages,
}
}
pub fn try_map<P, E, F>(self, f: F) -> Result<PaginatedData<P>, E>
where
F: FnMut(T) -> Result<P, E>,
{
Ok(PaginatedData {
items: self
.items
.into_iter()
.map(f)
.collect::<Result<Vec<_>, _>>()?,
total_count: self.total_count,
page: self.page,
page_size: self.page_size,
total_pages: self.total_pages,
})
}
}
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[cfg_attr(feature = "openapi", schema(bound = "T: ToSchema"))]
pub struct ListData<T> {
pub items: Vec<T>,
pub total_count: u64,
}
impl<T> ListData<T> {
pub fn new(items: Vec<T>) -> Self {
Self {
total_count: items.len() as u64,
items,
}
}
pub fn map<P, F>(self, f: F) -> ListData<P>
where
F: FnMut(T) -> P,
{
ListData {
items: self.items.into_iter().map(f).collect(),
total_count: self.total_count,
}
}
pub fn try_map<P, E, F>(self, f: F) -> Result<ListData<P>, E>
where
F: FnMut(T) -> Result<P, E>,
{
Ok(ListData {
items: self
.items
.into_iter()
.map(f)
.collect::<Result<Vec<_>, _>>()?,
total_count: self.total_count,
})
}
}