use std::env; extern crate dotenv; use dotenv::dotenv; use crate::models::photo_model::Photo; use crate::models::user_model::User; use futures::stream::TryStreamExt; use mongodb::{ bson::{doc, oid::ObjectId}, error::Error, results::{DeleteResult, InsertOneResult, UpdateResult}, Client, Collection, }; pub struct MongoRepo { user_col: Collection, photo_col: Collection, } impl MongoRepo { pub async fn init() -> Self { dotenv().ok(); let uri = match env::var("MONGOURI") { Ok(v) => v.to_string(), Err(_) => format!("Error loading env variable"), }; let client = Client::with_uri_str(uri).await.unwrap(); let db = client.database("photos"); let user_col: Collection = db.collection("User"); let photo_col: Collection = db.collection("Photo"); MongoRepo { user_col, photo_col, } } pub async fn create_user(&self, new_user: User) -> Result { let new_doc = User { id: None, username: new_user.username, email: new_user.email, password: new_user.password, }; let user = self .user_col .insert_one(new_doc, None) .await .ok() .expect("Error creating user"); Ok(user) } pub async fn get_user(&self, id: &String) -> Result { let obj_id = ObjectId::parse_str(id).unwrap(); let filter = doc! {"_id": obj_id}; let user_detail = self .user_col .find_one(filter, None) .await .ok() .expect("Error getting user's detail"); Ok(user_detail.unwrap()) } pub async fn get_user_from_email(&self, email: &String) -> Result { let filter = doc! {"email": email}; let user_detail = self .user_col .find_one(filter, None) .await .ok() .expect("Error getting user's detail"); Ok(user_detail.unwrap()) } pub async fn update_user(&self, id: &String, new_user: User) -> Result { let obj_id = ObjectId::parse_str(id).unwrap(); let filter = doc! {"_id": obj_id}; let new_doc = doc! { "$set": { "id": new_user.id, "username": new_user.username, "email": new_user.email, "password": new_user.password, }, }; let updated_doc = self .user_col .update_one(filter, new_doc, None) .await .ok() .expect("Error updating user"); Ok(updated_doc) } pub async fn delete_user(&self, id: &String) -> Result { let obj_id = ObjectId::parse_str(id).unwrap(); let filter = doc! {"_id": obj_id}; let user_detail = self .user_col .delete_one(filter, None) .await .ok() .expect("Error deleting user"); Ok(user_detail) } pub async fn create_photo(&self, new_photo: Photo) -> Result { let new_doc = Photo { id: None, user_id: new_photo.user_id, key: new_photo.key, width: new_photo.width, height: new_photo.height, }; let photo = self .photo_col .insert_one(new_doc, None) .await .ok() .expect("Error creating user"); Ok(photo) } pub async fn get_photos(&self, id: &String) -> Result, Error> { let obj_id = ObjectId::parse_str(id).unwrap(); let filter = doc! {"user_id": obj_id}; let mut cursor = self .photo_col .find(filter, None) .await .ok() .expect("Error getting photos cursor"); let mut photos = Vec::new(); while let Some(photo) = cursor.try_next().await? { photos.push(photo); } Ok(photos) } }