diff --git a/database_interactions/diesel/Cargo.toml b/database_interactions/diesel/Cargo.toml index 11324cd9..ca23379f 100644 --- a/database_interactions/diesel/Cargo.toml +++ b/database_interactions/diesel/Cargo.toml @@ -14,7 +14,6 @@ dotenv = "0.15" env_logger = "0.8" failure = "0.1.8" futures = "0.3.1" -r2d2 = "0.8" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" uuid = { version = "0.8", features = ["serde", "v4"] } diff --git a/database_interactions/diesel/src/actions.rs b/database_interactions/diesel/src/actions.rs index 97bd19c7..28cd6fb7 100644 --- a/database_interactions/diesel/src/actions.rs +++ b/database_interactions/diesel/src/actions.rs @@ -3,11 +3,13 @@ use uuid::Uuid; use crate::models; +type DbError = Box; + /// Run query using Diesel to find user by uid and return it. pub fn find_user_by_uid( uid: Uuid, conn: &SqliteConnection, -) -> Result, diesel::result::Error> { +) -> Result, DbError> { use crate::schema::users::dsl::*; let user = users @@ -23,7 +25,7 @@ pub fn insert_new_user( // prevent collision with `name` column imported inside the function nm: &str, conn: &SqliteConnection, -) -> Result { +) -> Result { // It is common when using Diesel with Actix web to import schema-related // modules inside a function's scope (rather than the normal module's scope) // to prevent import collisions and namespace pollution. diff --git a/database_interactions/diesel/src/main.rs b/database_interactions/diesel/src/main.rs index 42ceb2c7..4ff5df1b 100644 --- a/database_interactions/diesel/src/main.rs +++ b/database_interactions/diesel/src/main.rs @@ -24,15 +24,17 @@ async fn get_user( user_uid: web::Path, ) -> Result { let user_uid = user_uid.into_inner(); - let conn = pool.get().expect("couldn't get db connection from pool"); // use web::block to offload blocking Diesel code without blocking server thread - let user = web::block(move || actions::find_user_by_uid(user_uid, &conn)) - .await - .map_err(|e| { - eprintln!("{}", e); - HttpResponse::InternalServerError().finish() - })?; + let user = web::block(move || { + let conn = pool.get()?; + actions::find_user_by_uid(user_uid, &conn) + }) + .await + .map_err(|e| { + eprintln!("{}", e); + HttpResponse::InternalServerError().finish() + })?; if let Some(user) = user { Ok(HttpResponse::Ok().json(user)) @@ -49,15 +51,16 @@ async fn add_user( pool: web::Data, form: web::Json, ) -> Result { - let conn = pool.get().expect("couldn't get db connection from pool"); - // use web::block to offload blocking Diesel code without blocking server thread - let user = web::block(move || actions::insert_new_user(&form.name, &conn)) - .await - .map_err(|e| { - eprintln!("{}", e); - HttpResponse::InternalServerError().finish() - })?; + let user = web::block(move || { + let conn = pool.get()?; + actions::insert_new_user(&form.name, &conn) + }) + .await + .map_err(|e| { + eprintln!("{}", e); + HttpResponse::InternalServerError().finish() + })?; Ok(HttpResponse::Ok().json(user)) }