use serde::{Serialize, Deserialize}; use crate::database; use crate::types::response::{Result, ResponseCode}; #[derive(Serialize, Deserialize, Debug)] pub struct User { pub user_id: u64, pub firstname: String, pub lastname: String, pub email: String, pub password: String, pub gender: String, pub date: u64, pub day: u8, pub month: u8, pub year: u32, } impl User { pub fn from_user_id(user_id: u64, hide_password: bool) -> Result { let Ok(Some(user)) = database::users::get_user_by_id(user_id, hide_password) else { return Err(ResponseCode::BadRequest.text("User does not exist")) }; Ok(user) } pub fn from_user_ids(user_ids: Vec) -> Vec { user_ids.iter().map(|user_id| { let Ok(Some(user)) = database::users::get_user_by_id(*user_id, true) else { return None; }; Some(user) }).flatten().collect() } pub fn from_user_page(page: u64) -> Result> { let Ok(users) = database::users::get_user_page(page, true) else { return Err(ResponseCode::BadRequest.text("Failed to fetch users")) }; Ok(users) } pub fn from_email(email: &str) -> Result { let Ok(Some(user)) = database::users::get_user_by_email(email, false) else { return Err(ResponseCode::BadRequest.text("User does not exist")) }; Ok(user) } pub fn from_password(password: &str) -> Result { let Ok(Some(user)) = database::users::get_user_by_password(password, true) else { return Err(ResponseCode::BadRequest.text("User does not exist")) }; Ok(user) } pub fn new(firstname: String, lastname: String, email: String, password: String, gender: String, day: u8, month: u8, year: u32) -> Result { if let Ok(_) = User::from_email(&email) { return Err(ResponseCode::BadRequest.text(&format!("Email is already in use by {}", &email))) } if let Ok(user) = User::from_password(&password) { return Err(ResponseCode::BadRequest.text(&format!("Password is already in use by {}", user.email))) } let Ok(user) = database::users::add_user(&firstname, &lastname, &email, &password, &gender, day, month, year) else { return Err(ResponseCode::InternalServerError.text("Failed to create new uesr")) }; Ok(user) } }