use std::collections::BTreeMap;
use crate::context::Context;
use crate::error::{ErrorCode, JsonApiError};
pub const DEFAULT_PAGE_SIZE: usize = 25;
pub const MAX_PAGE_SIZE: usize = 100;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Page {
Offset {
offset: usize,
limit: usize,
},
Cursor {
after: Option<String>,
size: usize,
},
}
impl Default for Page {
fn default() -> Self {
Self::Offset {
offset: 0,
limit: DEFAULT_PAGE_SIZE,
}
}
}
impl Page {
pub fn size(&self) -> usize {
match self {
Self::Offset { limit, .. } => *limit,
Self::Cursor { size, .. } => *size,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sort {
field: String,
descending: bool,
}
impl Sort {
pub fn field(&self) -> &str {
&self.field
}
pub fn descending(&self) -> bool {
self.descending
}
}
#[derive(Debug, Clone, Default)]
pub struct Query {
page: Page,
sort: Vec<Sort>,
}
impl Query {
pub fn page(&self) -> &Page {
&self.page
}
pub fn sort(&self) -> &[Sort] {
&self.sort
}
pub fn parse(query: &str, ctx: &Context) -> Result<Self, JsonApiError> {
let params = split(query);
Ok(Self {
page: page_from(¶ms, ctx)?,
sort: sort_from(¶ms),
})
}
}
fn split(query: &str) -> BTreeMap<String, String> {
query
.split('&')
.filter(|pair| !pair.is_empty())
.map(|pair| match pair.split_once('=') {
Some((key, value)) => (decode(key), decode(value)),
None => (decode(pair), String::new()),
})
.collect()
}
fn decode(raw: &str) -> String {
let bytes = raw.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'+' => {
out.push(b' ');
i += 1;
}
b'%' if i + 2 < bytes.len() => {
let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok();
match hex.and_then(|h| u8::from_str_radix(h, 16).ok()) {
Some(byte) => {
out.push(byte);
i += 3;
}
None => {
out.push(b'%');
i += 1;
}
}
}
byte => {
out.push(byte);
i += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
fn page_from(params: &BTreeMap<String, String>, ctx: &Context) -> Result<Page, JsonApiError> {
let offset = params.get("page[offset]");
let limit = params.get("page[limit]");
let cursor = params.get("page[cursor]");
let size = params.get("page[size]");
let is_offset = offset.is_some() || limit.is_some();
let is_cursor = cursor.is_some() || size.is_some();
if is_offset && is_cursor {
return Err(invalid(
ctx,
"page",
"use either `page[offset]`/`page[limit]` or `page[cursor]`/`page[size]`, not both",
));
}
if is_cursor {
return Ok(Page::Cursor {
after: cursor.filter(|value| !value.is_empty()).cloned(),
size: number(size, "page[size]", DEFAULT_PAGE_SIZE, ctx)?.min(MAX_PAGE_SIZE),
});
}
Ok(Page::Offset {
offset: number(offset, "page[offset]", 0, ctx)?,
limit: number(limit, "page[limit]", DEFAULT_PAGE_SIZE, ctx)?.min(MAX_PAGE_SIZE),
})
}
fn number(
raw: Option<&String>,
name: &str,
default: usize,
ctx: &Context,
) -> Result<usize, JsonApiError> {
match raw {
None => Ok(default),
Some(value) => value.parse().map_err(|_| {
invalid(
ctx,
name,
format!("`{name}` must be a non-negative whole number, not `{value}`"),
)
}),
}
}
fn sort_from(params: &BTreeMap<String, String>) -> Vec<Sort> {
let Some(raw) = params.get("sort") else {
return Vec::new();
};
raw.split(',')
.map(str::trim)
.filter(|key| !key.is_empty() && *key != "-")
.map(|key| match key.strip_prefix('-') {
Some(field) => Sort {
field: field.to_string(),
descending: true,
},
None => Sort {
field: key.to_string(),
descending: false,
},
})
.collect()
}
fn invalid(ctx: &Context, parameter: &str, detail: impl Into<String>) -> JsonApiError {
JsonApiError::in_request(ErrorCode::InvalidParameter, ctx)
.detail(detail)
.parameter(parameter)
}
pub struct Paginator<'a> {
base: &'a str,
query: &'a Query,
}
impl<'a> Paginator<'a> {
pub fn new(base: &'a str, query: &'a Query) -> Self {
Self { base, query }
}
pub fn links(
&self,
returned: usize,
total: Option<usize>,
cursor: Option<&str>,
has_more: Option<bool>,
) -> crate::document::Links {
match self.query.page() {
Page::Offset { offset, limit } => {
self.offset_links(*offset, *limit, returned, total, has_more)
}
Page::Cursor { size, .. } => self.cursor_links(*size, cursor),
}
}
fn offset_links(
&self,
offset: usize,
limit: usize,
returned: usize,
total: Option<usize>,
has_more: Option<bool>,
) -> crate::document::Links {
let mut links = crate::document::Links::this(self.offset_url(offset, limit));
links = links.first(self.offset_url(0, limit));
if offset > 0 {
links = links.prev(self.offset_url(offset.saturating_sub(limit), limit));
}
let more = match (has_more, total) {
(Some(more), _) => more,
(None, Some(total)) => offset + returned < total,
(None, None) => returned == limit && limit > 0,
};
if more {
links = links.next(self.offset_url(offset + limit, limit));
}
if let Some(total) = total
&& limit > 0
{
let last = total.saturating_sub(1) / limit * limit;
links = links.last(self.offset_url(last, limit));
}
links
}
fn cursor_links(&self, size: usize, cursor: Option<&str>) -> crate::document::Links {
let current = match self.query.page() {
Page::Cursor { after, .. } => after.as_deref(),
Page::Offset { .. } => None,
};
let mut links = crate::document::Links::this(self.cursor_url(current, size));
if let Some(cursor) = cursor {
links = links.next(self.cursor_url(Some(cursor), size));
}
links
}
fn offset_url(&self, offset: usize, limit: usize) -> String {
format!(
"{}?page[offset]={offset}&page[limit]={limit}{}",
self.base,
self.sort_suffix()
)
}
fn cursor_url(&self, after: Option<&str>, size: usize) -> String {
match after {
Some(cursor) => format!(
"{}?page[cursor]={}&page[size]={size}{}",
self.base,
encode(cursor),
self.sort_suffix()
),
None => format!("{}?page[size]={size}{}", self.base, self.sort_suffix()),
}
}
fn sort_suffix(&self) -> String {
let keys = self.query.sort();
if keys.is_empty() {
return String::new();
}
let joined = keys
.iter()
.map(|key| {
if key.descending() {
format!("-{}", key.field())
} else {
key.field().to_string()
}
})
.collect::<Vec<_>>()
.join(",");
format!("&sort={}", encode(&joined))
}
}
fn encode(raw: &str) -> String {
raw.bytes()
.map(|byte| match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b',' => {
(byte as char).to_string()
}
other => format!("%{other:02X}"),
})
.collect()
}