dynamic_db #17
@@ -1,12 +1,52 @@
|
||||
use axum::{Json, http::StatusCode};
|
||||
// use sqlx::{Executor, PgPool, Row, postgres::PgPoolOptions}; // Added Row for potential use
|
||||
|
||||
use crate::models;
|
||||
|
||||
pub async fn register_user(
|
||||
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
|
||||
Json(payload): Json<models::common::CreateUser>,
|
||||
) -> (StatusCode, Json<models::common::User>) {
|
||||
let user = models::common::User {
|
||||
let mut user = models::common::User {
|
||||
id: uuid::Uuid::nil(),
|
||||
username: payload.username.clone(),
|
||||
password: payload.password.clone(),
|
||||
};
|
||||
(StatusCode::CREATED, Json(user))
|
||||
|
||||
let insert_sql = "INSERT INTO \"user\" (username, password) VALUES ($1, $2) RETURNING id";
|
||||
println!("SQL: {:?}", insert_sql);
|
||||
/*
|
||||
sqlx::query(insert_sql)
|
||||
.bind(&user.username)
|
||||
.bind(&user.password)
|
||||
.execute(&pool)
|
||||
.await;
|
||||
*/
|
||||
|
||||
/*
|
||||
let returned_id: uuid::Uuid = sqlx::query_scalar(insert_sql)
|
||||
.bind(&user.username)
|
||||
.bind(&user.password)
|
||||
.fetch_one(&pool).await? // fetch_one expects exactly one row
|
||||
*/
|
||||
let id = match sqlx::query_scalar(insert_sql)
|
||||
.bind(&user.username) // Bind the input message securely
|
||||
.bind(&user.password)
|
||||
.fetch_one(&pool) // Execute and expect exactly ONE row with ONE column back
|
||||
.await
|
||||
{
|
||||
Ok(o) => o,
|
||||
_ => {
|
||||
uuid::Uuid::nil()
|
||||
// (StatusCode::BAD_REQUEST, Json(user))
|
||||
}
|
||||
};
|
||||
|
||||
if id != uuid::Uuid::nil() {
|
||||
println!("User inserted.");
|
||||
user.id = id;
|
||||
(StatusCode::CREATED, Json(user))
|
||||
} else {
|
||||
(StatusCode::BAD_REQUEST, Json(user))
|
||||
}
|
||||
}
|
||||
|
@@ -3,9 +3,12 @@ use serde::{Deserialize, Serialize};
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateUser {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct User {
|
||||
pub id: uuid::Uuid,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
Reference in New Issue
Block a user