add custom message for failed to signup due to username being taken

This commit is contained in:
Mitchell Marino 2023-04-04 14:46:44 -05:00
parent a0e34f2135
commit e0e58811a8
2 changed files with 24 additions and 6 deletions

View File

@ -14,4 +14,4 @@ serde_json = "1.0"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
sha256 = "1.1"
jsonwebtoken = "8.3"

View File

@ -16,6 +16,8 @@ async fn main() {
// initialize tracing
tracing_subscriber::fmt::init();
// Ex.
// export DATABASE_URL="postgres://school_app_api_user:school_app_api_pass@localhost/school_app_api"
let db_url = std::env::var("DATABASE_URL")
.expect("Set `DATABASE_URL` to the url of the postgres database.");
@ -49,7 +51,6 @@ async fn root() -> &'static str {
}
async fn signup(State(pool): State<PgPool>, Json(signup): Json<Signup>) -> impl IntoResponse {
println!("{:?}", signup);
// insert your application logic here
let pass_hash = sha256::digest(&*signup.password);
@ -67,10 +68,27 @@ RETURNING id;
match result {
Ok(record) => (StatusCode::CREATED, Json(json!({"id": record.id}))),
Err(err) => (
Err(err) => {
// See if we get an error for a duplicate usename
if let sqlx::Error::Database(database_err) = &err {
if let Some(err_code) = database_err.code() {
if err_code == "23505" {
return (
StatusCode::BAD_REQUEST,
Json(json!({
"error": format!("username '{}' is taken.", signup.username)
})),
);
}
}
}
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "error": format!("Error signing up: {}", err) })),
),
Json(json!({
"error": format!("Unknown error signing up: {}", err)
})),
)
}
}
}