From f44d9de45d146aad787c7535170ea241fc531428 Mon Sep 17 00:00:00 2001 From: Teajey <21069848+Teajey@users.noreply.github.com> Date: Sat, 9 Mar 2024 16:06:43 +1300 Subject: [PATCH] feat: pagination --- src/route/frontmatter_list.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/route/frontmatter_list.rs b/src/route/frontmatter_list.rs index 690e6d1..5b19c8c 100644 --- a/src/route/frontmatter_list.rs +++ b/src/route/frontmatter_list.rs @@ -1,6 +1,5 @@ use std::collections::HashMap; -use anyhow::Result; use axum::{ extract::{Query, State}, http::StatusCode, @@ -42,6 +41,26 @@ fn sort_with_params(params: &HashMap, files: &mut [Short]) { files.reverse(); } +fn paginate(params: &HashMap, files: Vec) -> Result, StatusCode> { + let offset = params + .get("offset") + .map(|x| x.parse::()) + .transpose() + .map_err(|_| StatusCode::BAD_REQUEST)?; + let limit = params + .get("limit") + .map(|x| x.parse::()) + .transpose() + .map_err(|_| StatusCode::BAD_REQUEST)?; + let files = match (offset, limit) { + (None, None) => files, + (None, Some(limit)) => files.into_iter().take(limit).collect(), + (Some(offset), None) => files.into_iter().skip(offset).collect(), + (Some(offset), Some(limit)) => files.into_iter().skip(offset).take(limit).collect(), + }; + Ok(files) +} + fn get_inner( params: &HashMap, files: &frontmatter_file::keeper::ArcMutex, @@ -52,6 +71,8 @@ fn get_inner( sort_with_params(params, &mut files); + let files = paginate(params, files)?; + Ok(files) } @@ -79,6 +100,8 @@ fn post_inner( sort_with_params(params, &mut filtered_files); + let filtered_files = paginate(params, filtered_files)?; + Ok(filtered_files) }