From 3238fcb8f3fa55073481826693e1192ced413674 Mon Sep 17 00:00:00 2001 From: ElnuDev Date: Fri, 22 Jul 2022 15:37:57 -0700 Subject: [PATCH] Add persistent databases --- .gitignore | 1 + demo/soudan.js | 2 +- src/database.rs | 16 ++++++++++------ src/main.rs | 15 +++++++++++---- 4 files changed, 23 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index ea8c4bf..2c4918c 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +*.db diff --git a/demo/soudan.js b/demo/soudan.js index de8dbab..a58f7a0 100644 --- a/demo/soudan.js +++ b/demo/soudan.js @@ -17,7 +17,7 @@ ${commentForm()}

Comments

`; const md = window.markdownit().disable("image"); -const url = "http://127.0.0.1:8080"; +const url = "http://localhost:8080"; const form = document.getElementById("soudan-comment-form"); const commentContainer = document.getElementById("soudan-comments"); const commentContainerHeader = document.getElementById("soudan-comments-header"); diff --git a/src/database.rs b/src/database.rs index 97736b8..0e14a77 100644 --- a/src/database.rs +++ b/src/database.rs @@ -6,13 +6,17 @@ pub struct Database { } impl Database { - pub fn new(testing: bool) -> Result { - if !testing { - unimplemented!("Persistent databases unimplemented!"); - } - let conn = Connection::open_in_memory()?; + pub fn new(testing: bool, name: &str) -> Result { + let name = name + .replace("http://", "") + .replace("https://", ""); + let conn = if testing { + Connection::open_in_memory() + } else { + Connection::open(format!("{name}.db")) + }?; conn.execute( - "CREATE TABLE comment ( + "CREATE TABLE IF NOT EXISTS comment ( id INTEGER PRIMARY KEY, email TEXT, author TEXT, diff --git a/src/main.rs b/src/main.rs index 20891c1..3960af2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -203,7 +203,7 @@ async fn main() -> Result<(), std::io::Error> { for domain in domains.iter() { databases.insert( domain.to_owned(), - Mutex::new(Database::new(testing).unwrap()), + Mutex::new(Database::new(testing, domain).unwrap()), ); } let state = web::Data::new(AppState { databases }); @@ -212,11 +212,18 @@ async fn main() -> Result<(), std::io::Error> { .service(get_comments) .service(post_comment) .app_data(state.clone()) - .wrap(if testing { + // Issue with CORS on POST requests, + // keeping permissive for now + .wrap(Cors::permissive() /* if testing { Cors::permissive() } else { - Cors::default() - }) + let mut cors = Cors::default() + .allowed_methods(vec!["GET", "POST"]); + for domain in domains.iter() { + cors = cors.allowed_origin(domain); + } + cors + } */) }) .bind(("127.0.0.1", 8080))? .run()