about summary refs log tree commit diff
path: root/kittybox-rs/src/database/mod.rs
diff options
context:
space:
mode:
Diffstat (limited to 'kittybox-rs/src/database/mod.rs')
-rw-r--r--kittybox-rs/src/database/mod.rs102
1 files changed, 61 insertions, 41 deletions
diff --git a/kittybox-rs/src/database/mod.rs b/kittybox-rs/src/database/mod.rs
index 6bf5409..bd25d8d 100644
--- a/kittybox-rs/src/database/mod.rs
+++ b/kittybox-rs/src/database/mod.rs
@@ -55,8 +55,6 @@ pub struct StorageError {
     kind: ErrorKind,
 }
 
-impl warp::reject::Reject for StorageError {}
-
 impl std::error::Error for StorageError {
     fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
         self.source
@@ -75,18 +73,20 @@ impl From<serde_json::Error> for StorageError {
 }
 impl std::fmt::Display for StorageError {
     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-        match match self.kind {
-            ErrorKind::Backend => write!(f, "backend error: "),
-            ErrorKind::JsonParsing => write!(f, "error while parsing JSON: "),
-            ErrorKind::PermissionDenied => write!(f, "permission denied: "),
-            ErrorKind::NotFound => write!(f, "not found: "),
-            ErrorKind::BadRequest => write!(f, "bad request: "),
-            ErrorKind::Conflict => write!(f, "conflict with an in-flight request or existing data: "),
-            ErrorKind::Other => write!(f, "generic storage layer error: "),
-        } {
-            Ok(_) => write!(f, "{}", self.msg),
-            Err(err) => Err(err),
-        }
+        write!(
+            f,
+            "{}: {}",
+            match self.kind {
+                ErrorKind::Backend => "backend error",
+                ErrorKind::JsonParsing => "JSON parsing error",
+                ErrorKind::PermissionDenied => "permission denied",
+                ErrorKind::NotFound => "not found",
+                ErrorKind::BadRequest => "bad request",
+                ErrorKind::Conflict => "conflict with an in-flight request or existing data",
+                ErrorKind::Other => "generic storage layer error",
+            },
+            self.msg
+        )
     }
 }
 impl serde::Serialize for StorageError {
@@ -377,9 +377,11 @@ mod tests {
                     returned_post["properties"]["category"].as_array().unwrap(),
                     &vec![json!("testing")]
                 );
-            },
+            }
             something_else => {
-                something_else.expect("Shouldn't error").expect("Should have the post");
+                something_else
+                    .expect("Shouldn't error")
+                    .expect("Should have the post");
             }
         }
     }
@@ -411,7 +413,11 @@ mod tests {
 
     async fn test_settings<Backend: Storage>(backend: Backend) {
         backend
-            .set_setting(crate::database::Settings::SiteName, "https://fireburn.ru/", "Vika's Hideout")
+            .set_setting(
+                crate::database::Settings::SiteName,
+                "https://fireburn.ru/",
+                "Vika's Hideout",
+            )
             .await
             .unwrap();
         assert_eq!(
@@ -428,7 +434,9 @@ mod tests {
 
         let uid = format!(
             "https://{domain}/posts/{}-{}-{}",
-            rand::random::<Word>(), rand::random::<Word>(), rand::random::<Word>()
+            rand::random::<Word>(),
+            rand::random::<Word>(),
+            rand::random::<Word>()
         );
 
         let post = json!({
@@ -467,12 +475,16 @@ mod tests {
             .unwrap();
         println!("---");
         for (i, post) in posts.iter().enumerate() {
-            backend.put_post(post, "https://fireburn.ru/").await.unwrap();
+            backend
+                .put_post(post, "https://fireburn.ru/")
+                .await
+                .unwrap();
             println!("posts[{}] = {}", i, post["properties"]["uid"][0]);
         }
         println!("---");
         let limit: usize = 10;
-        let result = backend.read_feed_with_limit(key, &None, limit, &None)
+        let result = backend
+            .read_feed_with_limit(key, &None, limit, &None)
             .await
             .unwrap()
             .unwrap();
@@ -482,31 +494,38 @@ mod tests {
         println!("---");
         assert_eq!(result["children"].as_array().unwrap()[0..10], posts[0..10]);
 
-        let result2 = backend.read_feed_with_limit(
-            key,
-            &result["children"]
-                .as_array()
-                .unwrap()
-                .last()
-                .unwrap()
-                ["properties"]["uid"][0]
-                .as_str()
-                .map(|i| i.to_owned()),
-            limit, &None
-        ).await.unwrap().unwrap();
+        let result2 = backend
+            .read_feed_with_limit(
+                key,
+                &result["children"].as_array().unwrap().last().unwrap()["properties"]["uid"][0]
+                    .as_str()
+                    .map(|i| i.to_owned()),
+                limit,
+                &None,
+            )
+            .await
+            .unwrap()
+            .unwrap();
         for (i, post) in result2["children"].as_array().unwrap().iter().enumerate() {
             println!("feed[1][{}] = {}", i, post["properties"]["uid"][0]);
         }
         println!("---");
-        assert_eq!(result2["children"].as_array().unwrap()[0..10], posts[10..20]);
+        assert_eq!(
+            result2["children"].as_array().unwrap()[0..10],
+            posts[10..20]
+        );
 
         // Regression test for #4
         let nonsense_after = Some("1010101010".to_owned());
         let result3 = tokio::time::timeout(tokio::time::Duration::from_secs(10), async move {
-            backend.read_feed_with_limit(
-                key, &nonsense_after, limit, &None
-            ).await.unwrap().unwrap()
-        }).await.expect("Operation should not hang: see https://gitlab.com/kittybox/kittybox/-/issues/4");
+            backend
+                .read_feed_with_limit(key, &nonsense_after, limit, &None)
+                .await
+                .unwrap()
+                .unwrap()
+        })
+        .await
+        .expect("Operation should not hang: see https://gitlab.com/kittybox/kittybox/-/issues/4");
         assert!(result3["children"].as_array().unwrap().is_empty());
     }
 
@@ -520,20 +539,21 @@ mod tests {
                 $func_name!(test_update);
                 $func_name!(test_feed_pagination);
             }
-        }
+        };
     }
     macro_rules! file_test {
         ($func_name:ident) => {
             #[tokio::test]
-            async fn $func_name () {
+            async fn $func_name() {
                 test_logger::ensure_env_logger_initialized();
                 let tempdir = tempdir::TempDir::new("file").expect("Failed to create tempdir");
-                let backend = super::super::FileStorage::new(tempdir.into_path()).await.unwrap();
+                let backend = super::super::FileStorage::new(tempdir.into_path())
+                    .await
+                    .unwrap();
                 super::$func_name(backend).await
             }
         };
     }
 
     test_all!(file_test, file);
-
 }