Skip to content

Commit

Permalink
feat: pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
Teajey committed Mar 9, 2024
1 parent f060f3f commit f44d9de
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/route/frontmatter_list.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::collections::HashMap;

use anyhow::Result;
use axum::{
extract::{Query, State},
http::StatusCode,
Expand Down Expand Up @@ -42,6 +41,26 @@ fn sort_with_params(params: &HashMap<String, String>, files: &mut [Short]) {
files.reverse();
}

fn paginate(params: &HashMap<String, String>, files: Vec<Short>) -> Result<Vec<Short>, StatusCode> {
let offset = params
.get("offset")
.map(|x| x.parse::<usize>())
.transpose()
.map_err(|_| StatusCode::BAD_REQUEST)?;
let limit = params
.get("limit")
.map(|x| x.parse::<usize>())
.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<String, String>,
files: &frontmatter_file::keeper::ArcMutex,
Expand All @@ -52,6 +71,8 @@ fn get_inner(

sort_with_params(params, &mut files);

let files = paginate(params, files)?;

Ok(files)
}

Expand Down Expand Up @@ -79,6 +100,8 @@ fn post_inner(

sort_with_params(params, &mut filtered_files);

let filtered_files = paginate(params, filtered_files)?;

Ok(filtered_files)
}

Expand Down

0 comments on commit f44d9de

Please sign in to comment.