diff options
Diffstat (limited to 'src/data.rs')
-rw-r--r-- | src/data.rs | 22 |
1 files changed, 14 insertions, 8 deletions
diff --git a/src/data.rs b/src/data.rs index 574612a..396e932 100644 --- a/src/data.rs +++ b/src/data.rs @@ -7,7 +7,8 @@ pub struct Quote { date: String, author: String, score: String, - votes: u32, + points: i32, + votes: i32, content: String, } @@ -48,14 +49,14 @@ pub fn populate_test_db(c: &Connection) -> Result<()> { (1, 2), (1, 3), (1, 1), - (2, 3), - (2, 4); + (2, 1), + (2, 2); "#, )); Ok(()) } -fn internal_get_quotes(c: &Connection, id: Option<i64>) -> Result<Vec<Quote>> { +fn internal_get_quotes(c: &Connection, id: Option<i64>, ordering: &str) -> Result<Vec<Quote>> { let mut stmt = c.prepare( r#" SELECT q.id, q.timestamp, q.author, q.content, @@ -75,6 +76,7 @@ fn internal_get_quotes(c: &Connection, id: Option<i64>) -> Result<Vec<Quote>> { author: row.get(2), content: row.get(3), score: format!("{:.2}", row.get::<i32, f64>(4) / row.get::<i32, f64>(5)), + points: row.get(4), votes: row.get(5), } })?; @@ -83,17 +85,21 @@ fn internal_get_quotes(c: &Connection, id: Option<i64>) -> Result<Vec<Quote>> { .collect::<Result<Vec<Quote>>>(); // For some reason, the ordering from sqlite doesn't work. result.map(|mut queries| { - queries.sort_by_key(|q| -q.id); + if ordering == "score" { + queries.sort_by_key(|q| -(q.points / q.votes)); + } else { + queries.sort_by_key(|q| -q.id); + } queries }) } -pub fn get_quotes(c: &Connection) -> Result<Vec<Quote>> { - internal_get_quotes(c, None) +pub fn get_quotes(c: &Connection, ordering: &str) -> Result<Vec<Quote>> { + internal_get_quotes(c, None, ordering) } pub fn get_quote(c: &Connection, id: i64) -> Result<Quote> { - let quotes = internal_get_quotes(c, Some(id))?; + let quotes = internal_get_quotes(c, Some(id), "")?; quotes.into_iter().next().ok_or(LinoError::NotFound( format!("quote with id {}", id), )) |