Phase 2.2: MongoDB connection and models
This commit is contained in:
parent
1cf927f527
commit
154c3d1152
13 changed files with 544 additions and 5 deletions
44
backend/src/db/mod.rs
Normal file
44
backend/src/db/mod.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
use mongodb::{Client, Database, options::{ClientOptions, ServerApi, ServerApiVersion}};
|
||||
use anyhow::Result;
|
||||
|
||||
pub struct MongoDb {
|
||||
pub client: Client,
|
||||
pub database: Database,
|
||||
}
|
||||
|
||||
impl MongoDb {
|
||||
pub async fn new(uri: &str, database_name: &str) -> Result<Self> {
|
||||
let mut client_options = ClientOptions::parse(uri).await?;
|
||||
|
||||
let server_api = ServerApi::builder()
|
||||
.version(ServerApiVersion::V1)
|
||||
.build();
|
||||
client_options.server_api = Some(server_api);
|
||||
|
||||
let client = Client::with_options(client_options)?;
|
||||
let database = client.database(database_name);
|
||||
|
||||
Ok(MongoDb { client, database })
|
||||
}
|
||||
|
||||
pub fn get_database(&self) -> Database {
|
||||
self.database.clone()
|
||||
}
|
||||
|
||||
pub fn collection<T>(&self, name: &str) -> mongodb::Collection<T> {
|
||||
self.database.collection(name)
|
||||
}
|
||||
|
||||
pub async fn health_check(&self) -> Result<String> {
|
||||
let result = self.client
|
||||
.database("admin")
|
||||
.run_command(mongodb::bson::doc! { "ping": 1 }, None)
|
||||
.await?;
|
||||
|
||||
if result.get_i32("ok").unwrap_or(0) == 1 {
|
||||
Ok("connected".to_string())
|
||||
} else {
|
||||
Ok("error".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue