summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKjetil Orbekk <kjetil.orbekk@gmail.com>2017-07-09 06:05:51 -0400
committerKjetil Orbekk <kjetil.orbekk@gmail.com>2017-07-09 06:46:14 -0400
commit0f6edf2c76f21a5f5834bd8b7bc85217ff8c8f18 (patch)
treebf604133aff60102981780133d8943d3c899f861
parenta3db23d802017762fdb77fbb294e57720088576c (diff)
refactor: Get single quote with NotFound error
-rw-r--r--src/data.rs19
1 files changed, 15 insertions, 4 deletions
diff --git a/src/data.rs b/src/data.rs
index b5199e2..574612a 100644
--- a/src/data.rs
+++ b/src/data.rs
@@ -1,5 +1,5 @@
use rusqlite::Connection;
-use error::Result;
+use error::{Result, LinoError};
#[derive(Serialize, Debug, Clone)]
pub struct Quote {
@@ -55,20 +55,20 @@ pub fn populate_test_db(c: &Connection) -> Result<()> {
Ok(())
}
-pub fn get_quotes(c: &Connection) -> Result<Vec<Quote>> {
+fn internal_get_quotes(c: &Connection, id: Option<i64>) -> Result<Vec<Quote>> {
let mut stmt = c.prepare(
r#"
SELECT q.id, q.timestamp, q.author, q.content,
sum(v.score), count(v.score)
FROM quotes q
JOIN votes v ON (q.id = v.quote_id)
- WHERE q.approved
+ WHERE (?1 AND q.id = ?2) OR (NOT ?1 AND q.approved)
GROUP BY 1, 2, 3, 4;
ORDER BY q.id DESC;
"#,
)?;
- let mut rows = stmt.query_map(&[], |row| {
+ let rows = stmt.query_map(&[&id.is_some(), &id.unwrap_or(-1)], |row| {
Quote {
id: row.get(0),
date: row.get(1),
@@ -87,3 +87,14 @@ pub fn get_quotes(c: &Connection) -> Result<Vec<Quote>> {
queries
})
}
+
+pub fn get_quotes(c: &Connection) -> Result<Vec<Quote>> {
+ internal_get_quotes(c, None)
+}
+
+pub fn get_quote(c: &Connection, id: i64) -> Result<Quote> {
+ let quotes = internal_get_quotes(c, Some(id))?;
+ quotes.into_iter().next().ok_or(LinoError::NotFound(
+ format!("quote with id {}", id),
+ ))
+}