diff --git a/src/callers/register.rs b/src/callers/register.rs index a17d2bc..a966c01 100644 --- a/src/callers/register.rs +++ b/src/callers/register.rs @@ -50,16 +50,37 @@ pub async fn register_user( last_login: String::from("nil"), }; - match repo::user::insert(&pool, &user).await { - Ok(id) => { - user.id = id; - ( - StatusCode::CREATED, - Json(response::Response { - message: String::from("User inserted"), - data: vec![user], - }), - ) + match repo::user::exists(&pool, &user.username).await { + Ok(res) => { + if res { + return ( + StatusCode::NOT_FOUND, + Json(response::Response { + message: String::from("Error"), + data: vec![user], + }), + ); + } else { + match repo::user::insert(&pool, &user).await { + Ok(id) => { + user.id = id; + ( + StatusCode::CREATED, + Json(response::Response { + message: String::from("User inserted"), + data: vec![user], + }), + ) + } + Err(err) => ( + StatusCode::BAD_REQUEST, + Json(response::Response { + message: err.to_string(), + data: vec![user], + }), + ), + } + } } Err(err) => ( StatusCode::BAD_REQUEST, diff --git a/src/repo/mod.rs b/src/repo/mod.rs index 48d6b59..744ced5 100644 --- a/src/repo/mod.rs +++ b/src/repo/mod.rs @@ -7,6 +7,26 @@ pub mod user { pub date_created: Option, } + pub async fn exists(pool: &sqlx::PgPool, username: &String) -> Result { + let result = sqlx::query( + r#" + SELECT 1 FROM "user" WHERE username = $1 + "#, + ) + .bind(&username) + .fetch_optional(pool) + .await; + + match result { + Ok(r) => Ok(r.is_some()), + Err(e) => { + println!("Error: {:?}", e.to_string()); + // Err(e) + Err(e) + } + } + } + pub async fn insert( pool: &sqlx::PgPool, user: &icarus_models::user::User,