Get working boilerplate

main
Elnu 2 years ago
parent 59f3ce9ea5
commit 4cfa06f855

@ -0,0 +1,5 @@
#[derive(Debug)]
pub struct Comment {
pub author: Option<String>, // null is Anonymous
pub text: String
}

@ -0,0 +1,41 @@
use rusqlite::{params, Connection, Result};
use crate::comment::Comment;
pub struct Database {
conn: Connection,
}
impl Database {
pub fn new() -> Result<Self> {
let conn = Connection::open_in_memory()?;
conn.execute(
"CREATE TABLE comment (
id INTEGER PRIMARY KEY,
author TEXT,
text TEXT NOT NULL
)",
params![]
)?;
Ok(Self { conn })
}
pub fn get_comments(&self) -> Result<Vec<Comment>> {
self.conn
.prepare("SELECT author, text FROM comment")?
.query_map([], |row| {
Ok(Comment {
author: row.get(0)?,
text: row.get(1)?,
})
})?
.collect()
}
pub fn create_comment(&self, comment: &Comment) -> Result<()> {
self.conn.execute(
"INSERT INTO comment (author, text) VALUES (?1, ?2)",
params![&comment.author, &comment.text],
)?;
Ok(())
}
}

@ -1,59 +1,31 @@
use rusqlite::{params, Connection, Result}; mod comment;
pub use comment::Comment;
#[derive(Debug)] mod database;
struct Comment { pub use database::Database;
author: Option<String>, // null is Anonymous
text: String
}
struct Database { use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};
conn: Connection use std::sync::{LockResult, Mutex};
}
impl Database { #[get("/comments")]
fn new() -> Result<Self> { async fn get_comments(data: web::Data<AppState>) -> impl Responder {
let conn = Connection::open_in_memory()?; let db = &data.db.lock().unwrap();
conn.execute( /*db.create_comment(&Comment {
"CREATE TABLE comment ( author: Some("Elnu".to_string()),
id INTEGER PRIMARY KEY, text: "Hello world".to_string()
author TEXT, }).unwrap();*/
text TEXT NOT NULL HttpResponse::Ok().body(format!("{}", db.get_comments().unwrap().get(0).unwrap_or(&Comment { author: None, text: "No comments yet!".to_string() }).text))
)",
params![]
)?;
Ok(Self { conn })
} }
fn get_comments(&self) -> Result<Vec<Comment>> { #[actix_web::main]
self.conn async fn main() -> Result<(), std::io::Error> {
.prepare("SELECT author, text FROM comment")? let state = web::Data::new(AppState { db: Mutex::new(Database::new().unwrap()) });
.query_map([], |row| { HttpServer::new(move || {
Ok(Comment { App::new()
author: row.get(0)?, .service(get_comments)
text: row.get(1)?, .app_data(state.clone())
}) })
})? .bind(("127.0.0.1", 8080))?
.collect() .run()
} .await
fn create_comment(&self, comment: &Comment) -> Result<()> {
self.conn.execute(
"INSERT INTO comment (author, text) VALUES (?1, ?2)",
params![&comment.author, &comment.text],
)?;
Ok(())
}
}
fn main() -> Result<()> {
let db = Database::new()?;
let comment = Comment {
author: Some("Elnu".to_string()), // None for anonymous
text: "This is a test comment by yours truly!".to_string(),
};
db.create_comment(&comment)?;
for comment in db.get_comments()?.iter() {
println!("Found comment {:?}", comment);
}
Ok(())
} }

Loading…
Cancel
Save