r2_data_persistence/operations/
user.rs1use crate::entities::User;
2use crate::models::user::{CreateUserModel, GetUserModel, UpdateUserModel};
3use crate::schema::user::dsl::*;
4use diesel::associations::HasTable;
5use diesel::prelude::*;
6use uuid::Uuid;
7
8pub fn create_user(
9 connection: &mut PgConnection,
10 model: CreateUserModel,
11) -> Result<GetUserModel, String> {
12 let result = diesel::insert_into(user::table())
13 .values(to_entity(model))
14 .returning(User::as_returning())
15 .get_result(connection);
16
17 match result {
18 Ok(entity) => Ok(to_model(entity)),
19 Err(error) => Err(format!("Error creating user: {}", error)),
20 }
21}
22
23pub fn get_user(connection: &mut PgConnection, key: &str) -> Option<GetUserModel> {
24 let result: QueryResult<User> = user.find(key).select(User::as_select()).first(connection);
25
26 if let Ok(entity) = result {
27 return Some(to_model(entity));
28 }
29
30 None
31}
32
33pub fn get_all_users(connection: &mut PgConnection) -> Result<Vec<GetUserModel>, String> {
34 let result = user.select(User::as_select()).load(connection);
35
36 match result {
37 Ok(entities) => Ok(entities.into_iter().map(to_model).collect()),
38 Err(error) => Err(format!("Error getting users: {}", error)),
39 }
40}
41
42pub fn update_user(
43 connection: &mut PgConnection,
44 key: &str,
45 model: UpdateUserModel,
46) -> Result<GetUserModel, String> {
47 let result = diesel::update(user.find(key))
48 .set::<UpdateUserModel>(model)
49 .returning(User::as_returning())
50 .get_result(connection);
51
52 match result {
53 Ok(entity) => Ok(to_model(entity)),
54 Err(error) => Err(format!("Error updating user: {}", error)),
55 }
56}
57
58pub fn delete_user(connection: &mut PgConnection, key: &str) -> Result<(), String> {
59 let result = diesel::delete(user.find(key)).execute(connection);
60
61 match result {
62 Ok(_) => Ok(()),
63 Err(error) => Err(format!("Error deleting user: {}", error)),
64 }
65}
66
67fn to_model(entity: User) -> GetUserModel {
68 GetUserModel {
69 id: entity.id,
70 email: entity.email,
71 username: entity.username,
72 profile_picture: entity.profile_picture,
73 all_time_accuracy: entity.all_time_accuracy,
74 all_time_highscore: entity.all_time_highscore,
75 rank: entity.rank,
76 percent: entity.percent,
77 }
78}
79
80fn to_entity(model: CreateUserModel) -> User {
81 User {
82 id: Uuid::new_v4().to_string(),
83 email: model.email,
84 password: model.password,
85 username: model.username,
86 profile_picture: model.profile_picture,
87 all_time_accuracy: model.all_time_accuracy,
88 all_time_highscore: model.all_time_highscore,
89 rank: model.rank,
90 percent: model.percent,
91 }
92}