Add timestamps, remove dead code

This commit is contained in:
Elnu 2022-07-08 18:38:53 -07:00
parent 82e70178d5
commit 0e270e18b9
5 changed files with 78 additions and 27 deletions

View file

@ -1,11 +1,12 @@
use serde::{Deserialize, Serialize};
use chrono::NaiveDateTime;
// Master comment type that is stored in database
#[derive(Deserialize, Serialize)]
pub struct Comment {
pub author: Option<String>, // None/null is Anonymous
pub email: Option<String>,
pub text: String
pub text: String,
pub timestamp: Option<NaiveDateTime>,
}
impl Comment {
@ -17,6 +18,7 @@ impl Comment {
None => None,
},
text: self.text.clone(),
timestamp: self.timestamp.unwrap().timestamp(),
}
}
}
@ -26,7 +28,8 @@ impl Comment {
pub struct CommentSend {
pub author: Option<String>,
pub gravatar: Option<String>,
pub text: String
pub text: String,
pub timestamp: i64,
}
// Comment type received containing new comment data
@ -43,6 +46,7 @@ impl CommentReceive {
author: self.author.clone(),
email: self.email.clone(),
text: self.text.clone(),
timestamp: None,
}
}
}

View file

@ -1,5 +1,6 @@
use rusqlite::{params, Connection, Result};
use crate::comment::{Comment, CommentSend};
use chrono::NaiveDateTime;
pub struct Database {
conn: Connection,
@ -10,33 +11,23 @@ impl Database {
let conn = Connection::open_in_memory()?;
conn.execute(
"CREATE TABLE comment (
id INTEGER PRIMARY KEY,
email TEXT,
author TEXT,
text TEXT NOT NULL
id INTEGER PRIMARY KEY,
email TEXT,
author TEXT,
text TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)",
params![]
)?;
Ok(Self { conn })
}
pub fn get_comments(&self) -> Result<Vec<Comment>> {
self.conn
.prepare("SELECT author, email, text FROM comment")?
.query_map([], |row| {
Ok(Comment {
author: row.get(0)?,
email: row.get(1)?,
text: row.get(2)?,
})
})?
.collect()
}
pub fn get_send_comments(&self) -> Result<Vec<CommentSend>> {
self.conn
.prepare("SELECT author, email, text FROM comment")?
.prepare("SELECT author, email, text, timestamp FROM comment")?
.query_map([], |row| {
let timestamp: NaiveDateTime = row.get(3)?;
let timestamp = timestamp.timestamp();
Ok(CommentSend {
author: row.get(0)?,
gravatar: match row.get::<usize, Option<String>>(1)? {
@ -44,6 +35,7 @@ impl Database {
None => None,
},
text: row.get(2)?,
timestamp: timestamp,
})
})?
.collect()

View file

@ -13,7 +13,10 @@ struct AppState {
#[get("/")]
async fn get_comments(data: web::Data<AppState>) -> impl Responder {
let db = &data.db.lock().unwrap();
let db = match data.db.lock() {
Ok(db) => db,
Err(_) => return HttpResponse::InternalServerError().into(),
};
HttpResponse::Ok().json(&db.get_send_comments().unwrap())
}