From 91186e5f4353601e196bb7cf863ca64b3c95e5bc Mon Sep 17 00:00:00 2001 From: ElnuDev Date: Fri, 8 Jul 2022 13:00:25 -0700 Subject: [PATCH] Create working comments API response --- Cargo.lock | 14 ++++++++++++++ Cargo.toml | 2 +- src/comment.rs | 2 +- src/main.rs | 13 +++++++------ 4 files changed, 23 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0acbf0c..433f240 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -886,6 +886,20 @@ name = "serde" version = "1.0.138" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1578c6245786b9d168c5447eeacfb96856573ca56c9d68fdcf394be134882a47" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.138" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "023e9b1467aef8a10fb88f25611870ada9800ef7e22afce356bb0d2387b6f27c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "serde_json" diff --git a/Cargo.toml b/Cargo.toml index f1d28d6..d703844 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,5 +8,5 @@ edition = "2021" [dependencies] actix-web = "4" rusqlite = "0.27.0" -serde = "1" +serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/src/comment.rs b/src/comment.rs index 771cfef..a8077ad 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -1,4 +1,4 @@ -#[derive(Debug)] +#[derive(Debug, serde::Serialize)] pub struct Comment { pub author: Option, // null is Anonymous pub text: String diff --git a/src/main.rs b/src/main.rs index 0cc3a30..27d599d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,16 +14,17 @@ struct AppState { #[get("/comments")] async fn get_comments(data: web::Data) -> impl Responder { let db = &data.db.lock().unwrap(); - /*db.create_comment(&Comment { - author: Some("Elnu".to_string()), - text: "Hello world".to_string() - }).unwrap();*/ - HttpResponse::Ok().body(format!("{}", db.get_comments().unwrap().get(0).unwrap_or(&Comment { author: None, text: "No comments yet!".to_string() }).text)) + HttpResponse::Ok().json(&db.get_comments().unwrap()) } #[actix_web::main] async fn main() -> Result<(), std::io::Error> { - let state = web::Data::new(AppState { db: Mutex::new(Database::new().unwrap()) }); + let db = Database::new().unwrap(); + db.create_comment(&Comment { + author: None, + text: "This is anonymous test comment!".to_string(), + }).unwrap(); + let state = web::Data::new(AppState { db: Mutex::new(db) }); HttpServer::new(move || { App::new() .service(get_comments)