forked from Txio-labs/txio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser_repository.rs
More file actions
82 lines (62 loc) · 2.2 KB
/
Copy pathuser_repository.rs
File metadata and controls
82 lines (62 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use mongodb::{Client, Collection};
use crate::model::user::User;
use crate::utils::error::AppError;
use mongodb::bson::doc;
use mongodb::bson::oid::ObjectId;
#[derive(Clone)]
pub struct UserRepository {
collection: Collection<User>,
}
impl UserRepository {
pub fn new(db: &Client) -> Self {
let collection = db.database("txio_db").collection("users");
Self { collection }
}
pub async fn save(&self, user: &User) -> Result<User, AppError> {
let result = self.collection
.insert_one(user, None)
.await?;
let mut user_with_id = user.clone();
if let Some(inserted_id) = result.inserted_id.as_object_id() {
user_with_id.id = Some(inserted_id);
}
Ok(user_with_id)
}
pub async fn find_by_email(&self, email: &str) -> Result<User, AppError> {
let user = self
.collection
.find_one(doc! { "email": email }, None)
.await?
.ok_or(AppError::NotFound("User not found with email".to_string()))?;
Ok(user)
}
pub async fn find_by_id(&self, id: &ObjectId) -> Result<User, AppError> {
let user = self
.collection
.find_one(doc! { "_id": id }, None)
.await?
.ok_or(AppError::NotFound("User not found".to_string()))?;
Ok(user)
}
pub async fn delete_by_id(&self, id: &str) -> Result<User, AppError> {
let object_id = ObjectId::parse_str(id)
.map_err(|_| AppError::BadRequest("Invalid user ID format".into()))?;
let user = self
.collection
.find_one_and_delete(doc! { "_id": object_id }, None)
.await?
.ok_or_else(|| AppError::NotFound("User not found".into()))?;
Ok(user)
}
pub async fn update(&self, user: &User) -> Result<User, AppError> {
println!("Updating user: {:?}", user);
let object_id = user
.id
.clone()
.ok_or_else(|| AppError::BadRequest("User ID is missing".into()))?;
self.collection
.replace_one(doc! { "_id": object_id }, user, None)
.await?;
Ok(user.clone())
}
}