add custom message for failed to signup due to username being taken
This commit is contained in:
parent
a0e34f2135
commit
e0e58811a8
@ -14,4 +14,4 @@ serde_json = "1.0"
|
|||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
sha256 = "1.1"
|
sha256 = "1.1"
|
||||||
|
jsonwebtoken = "8.3"
|
||||||
|
|||||||
28
src/main.rs
28
src/main.rs
@ -16,6 +16,8 @@ async fn main() {
|
|||||||
// initialize tracing
|
// initialize tracing
|
||||||
tracing_subscriber::fmt::init();
|
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")
|
let db_url = std::env::var("DATABASE_URL")
|
||||||
.expect("Set `DATABASE_URL` to the url of the postgres database.");
|
.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 {
|
async fn signup(State(pool): State<PgPool>, Json(signup): Json<Signup>) -> impl IntoResponse {
|
||||||
println!("{:?}", signup);
|
|
||||||
// insert your application logic here
|
// insert your application logic here
|
||||||
let pass_hash = sha256::digest(&*signup.password);
|
let pass_hash = sha256::digest(&*signup.password);
|
||||||
|
|
||||||
@ -67,10 +68,27 @@ RETURNING id;
|
|||||||
|
|
||||||
match result {
|
match result {
|
||||||
Ok(record) => (StatusCode::CREATED, Json(json!({"id": record.id}))),
|
Ok(record) => (StatusCode::CREATED, Json(json!({"id": record.id}))),
|
||||||
Err(err) => (
|
Err(err) => {
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
// See if we get an error for a duplicate usename
|
||||||
Json(json!({ "error": format!("Error signing up: {}", err) })),
|
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!("Unknown error signing up: {}", err)
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user