use crate::db::get_client; use crate::errors::AppError; use serde::{Deserialize, Serialize}; use validator::Validate; #[derive(Deserialize, Serialize, Validate)] pub struct User { id: i32, #[validate(length(min = 1, message = "Can not be empty"))] email: String, #[validate(length(min = 8, message = "Must be min 8 chars length"))] password: String, is_staff: Option, } #[derive(Deserialize, Serialize)] pub struct UserList { id: i32, email: String, is_staff: Option, } #[derive(Deserialize)] pub struct UserCreate { pub email: String, pub password: String, } impl User { pub fn new(email: String, password: String) -> Self { Self { id: 0, email, password, is_staff: Some(false), } } pub async fn create(user: User) -> Result { let pool = unsafe { get_client() }; let rec = sqlx::query_as!( UserList, r#" INSERT INTO users (email, password) VALUES ( $1, $2 ) RETURNING id, email, is_staff "#, user.email, sha256::digest(user.password) ) .fetch_one(pool) .await?; Ok(rec) } pub async fn list() -> Result, AppError> { let pool = unsafe { get_client() }; let rows = sqlx::query_as!(UserList, r#"SELECT id, email, is_staff FROM users"#) .fetch_all(pool) .await?; Ok(rows) } }