#[macro_use] extern crate rocket; #[macro_use] extern crate diesel; #[macro_use] extern crate diesel_migrations; #[macro_use] extern crate log; #[macro_use] extern crate rocket_contrib; mod task; #[cfg(test)] mod tests; use rocket::Rocket; use rocket::fairing::AdHoc; use rocket::request::{Form, FlashMessage}; use rocket::response::{Flash, Redirect}; use rocket_contrib::{templates::Template, serve::{StaticFiles, crate_relative}}; use diesel::SqliteConnection; use crate::task::{Task, Todo}; // This macro from `diesel_migrations` defines an `embedded_migrations` module // containing a function named `run`. This allows the example to be run and // tested without any outside setup of the database. embed_migrations!(); #[database("sqlite_database")] pub struct DbConn(SqliteConnection); #[derive(Debug, serde::Serialize)] struct Context { msg: Option<(String, String)>, tasks: Vec } impl Context { pub async fn err(conn: DbConn, msg: String) -> Context { Context { msg: Some(("error".to_string(), msg)), tasks: Task::all(conn).await.unwrap_or_default() } } pub async fn raw(conn: DbConn, msg: Option<(String, String)>) -> Context { match Task::all(conn).await { Ok(tasks) => Context { msg, tasks }, Err(e) => { error_!("DB Task::all() error: {}", e); Context { msg: Some(("error".to_string(), "Couldn't access the task database.".to_string())), tasks: vec![] } } } } } #[post("/", data = "")] async fn new(todo_form: Form, conn: DbConn) -> Flash { let todo = todo_form.into_inner(); if todo.description.is_empty() { Flash::error(Redirect::to("/"), "Description cannot be empty.") } else if let Err(e) = Task::insert(todo, conn).await { error_!("DB insertion error: {}", e); Flash::error(Redirect::to("/"), "Todo could not be inserted due an internal error.") } else { Flash::success(Redirect::to("/"), "Todo successfully added.") } } #[put("/")] async fn toggle(id: i32, mut conn: DbConn) -> Result { // TODO let conn2 = conn.clone().await.unwrap(); match Task::toggle_with_id(id, conn).await { Ok(_) => Ok(Redirect::to("/")), Err(e) => { error_!("DB toggle({}) error: {}", id, e); Err(Template::render("index", Context::err(conn2, "Failed to toggle task.".to_string()).await)) } } } #[delete("/")] async fn delete(id: i32, mut conn: DbConn) -> Result, Template> { // TODO let conn2 = conn.clone().await.unwrap(); match Task::delete_with_id(id, conn).await { Ok(_) => Ok(Flash::success(Redirect::to("/"), "Todo was deleted.")), Err(e) => { error_!("DB deletion({}) error: {}", id, e); Err(Template::render("index", Context::err(conn2, "Failed to delete task.".to_string()).await)) } } } #[get("/")] async fn index(msg: Option>, conn: DbConn) -> Template { let msg = msg.map(|m| (m.name().to_string(), m.msg().to_string())); Template::render("index", Context::raw(conn, msg).await) } async fn run_db_migrations(mut rocket: Rocket) -> Result { let conn = DbConn::get_one(rocket.inspect().await).await.expect("database connection"); conn.run(|c| { match embedded_migrations::run(c) { Ok(()) => Ok(rocket), Err(e) => { error!("Failed to run database migrations: {:?}", e); Err(rocket) } } }).await } #[launch] fn rocket() -> Rocket { rocket::ignite() .attach(DbConn::fairing()) .attach(AdHoc::on_attach("Database Migrations", run_db_migrations)) .mount("/", StaticFiles::from(crate_relative!("/static"))) .mount("/", routes![index]) .mount("/todo", routes![new, toggle, delete]) .attach(Template::fairing()) }