Skip to content

Include next_page and prev_page metadata on search #1763

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ futures = "0.1"
tokio = "0.1"
hyper = "0.12"
ctrlc = { version = "3.0", features = ["termination"] }
indexmap = "1.0.2"

[dev-dependencies]
conduit-test = "0.8"
Expand Down
5 changes: 3 additions & 2 deletions src/controllers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,15 @@ mod prelude {
use std::collections::HashMap;
use std::io;

use indexmap::IndexMap;
use serde::Serialize;
use url;

pub trait RequestUtils {
fn redirect(&self, url: String) -> Response;

fn json<T: Serialize>(&self, t: &T) -> Response;
fn query(&self) -> HashMap<String, String>;
fn query(&self) -> IndexMap<String, String>;
fn wants_json(&self) -> bool;
fn pagination(&self, default: usize, max: usize) -> CargoResult<(i64, i64)>;
}
Expand All @@ -31,7 +32,7 @@ mod prelude {
crate::util::json_response(t)
}

fn query(&self) -> HashMap<String, String> {
fn query(&self) -> IndexMap<String, String> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IndexMap defaults to the RandomState hasher from std, so this looks fine from a DOS perspective.

url::form_urlencoded::parse(self.query_string().unwrap_or("").as_bytes())
.map(|(a, b)| (a.into_owned(), b.into_owned()))
.collect()
Expand Down
29 changes: 28 additions & 1 deletion src/controllers/krate/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,27 @@ pub fn search(req: &mut dyn Request) -> CargoResult<Response> {
)
.collect();

let mut next_page = None;
let mut prev_page = None;
let page_num = params.get("page").map(|s| s.parse()).unwrap_or(Ok(1))?;

let url_for_page = |num: i64| {
let mut params = req.query();
params.insert("page".into(), num.to_string());
let query_string = url::form_urlencoded::Serializer::new(String::new())
.clear()
.extend_pairs(params)
.finish();
Some(format!("?{}", query_string))
};

if offset + limit < total {
next_page = url_for_page(page_num + 1);
}
if page_num != 1 {
prev_page = url_for_page(page_num - 1);
};

#[derive(Serialize)]
struct R {
crates: Vec<EncodableCrate>,
Expand All @@ -230,10 +251,16 @@ pub fn search(req: &mut dyn Request) -> CargoResult<Response> {
#[derive(Serialize)]
struct Meta {
total: i64,
next_page: Option<String>,
prev_page: Option<String>,
}

Ok(req.json(&R {
crates,
meta: Meta { total },
meta: Meta {
total,
next_page,
prev_page,
},
}))
}
2 changes: 2 additions & 0 deletions src/tests/all.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ pub struct CrateList {
#[derive(Deserialize)]
struct CrateMeta {
total: i32,
next_page: Option<String>,
prev_page: Option<String>,
}
#[derive(Deserialize)]
pub struct CrateResponse {
Expand Down
23 changes: 23 additions & 0 deletions src/tests/krate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2172,3 +2172,26 @@ fn publish_rate_limit_doesnt_affect_existing_crates() {
token.enqueue_publish(new_version).good();
app.run_pending_background_jobs();
}

#[test]
fn pagination_links_included_if_applicable() {
let (app, anon, user) = TestApp::init().with_user();
let user = user.as_model();

app.db(|conn| {
CrateBuilder::new("pagination_links_1", user.id).expect_build(conn);
CrateBuilder::new("pagination_links_2", user.id).expect_build(conn);
CrateBuilder::new("pagination_links_3", user.id).expect_build(conn);
});

let page1 = anon.search("per_page=1");
let page2 = anon.search("page=2&per_page=1");
let page3 = anon.search("page=3&per_page=1");

assert_eq!(Some("?per_page=1&page=2".to_string()), page1.meta.next_page);
assert_eq!(None, page1.meta.prev_page);
assert_eq!(Some("?page=3&per_page=1".to_string()), page2.meta.next_page);
assert_eq!(Some("?page=1&per_page=1".to_string()), page2.meta.prev_page);
assert_eq!(None, page3.meta.next_page);
assert_eq!(Some("?page=2&per_page=1".to_string()), page3.meta.prev_page);
}