mirror of
https://github.com/stoatchat/stoatchat.git
synced 2026-07-14 21:47:02 +00:00
refactor: combine models and db crate together
This commit is contained in:
@@ -1,4 +0,0 @@
|
||||
database_derived!(
|
||||
/// Dummy implementation
|
||||
pub struct DummyDb {}
|
||||
);
|
||||
@@ -1,5 +1,51 @@
|
||||
mod dummy;
|
||||
mod mongodb;
|
||||
mod reference;
|
||||
|
||||
pub use self::dummy::*;
|
||||
pub use self::mongodb::*;
|
||||
pub use self::reference::*;
|
||||
|
||||
/// Database information to use to create a client
|
||||
pub enum DatabaseInfo {
|
||||
/// Auto-detect the database in use
|
||||
Auto,
|
||||
/// Use the mock database
|
||||
Reference,
|
||||
/// Connect to MongoDB
|
||||
MongoDb(String),
|
||||
/// Use existing MongoDB connection
|
||||
MongoDbFromClient(::mongodb::Client),
|
||||
}
|
||||
|
||||
/// Database
|
||||
#[derive(Clone)]
|
||||
pub enum Database {
|
||||
/// Mock database
|
||||
Reference(ReferenceDb),
|
||||
/// MongoDB database
|
||||
MongoDb(MongoDb),
|
||||
}
|
||||
|
||||
impl DatabaseInfo {
|
||||
/// Create a database client from the given database information
|
||||
#[async_recursion]
|
||||
pub async fn connect(self) -> Result<Database, String> {
|
||||
Ok(match self {
|
||||
DatabaseInfo::Auto => {
|
||||
if let Ok(uri) = std::env::var("MONGODB") {
|
||||
return DatabaseInfo::MongoDb(uri).connect().await;
|
||||
}
|
||||
|
||||
DatabaseInfo::Reference.connect().await?
|
||||
}
|
||||
DatabaseInfo::Reference => Database::Reference(Default::default()),
|
||||
DatabaseInfo::MongoDb(uri) => {
|
||||
let client = ::mongodb::Client::with_uri_str(uri)
|
||||
.await
|
||||
.map_err(|_| "Failed to init db connection.".to_string())?;
|
||||
|
||||
Database::MongoDb(MongoDb(client))
|
||||
}
|
||||
DatabaseInfo::MongoDbFromClient(client) => Database::MongoDb(MongoDb(client)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
13
crates/core/database/src/drivers/reference.rs
Normal file
13
crates/core/database/src/drivers/reference.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use futures::lock::Mutex;
|
||||
|
||||
use crate::Bot;
|
||||
|
||||
database_derived!(
|
||||
/// Reference implementation
|
||||
#[derive(Default)]
|
||||
pub struct ReferenceDb {
|
||||
pub bots: Arc<Mutex<HashMap<String, Bot>>>,
|
||||
}
|
||||
);
|
||||
Reference in New Issue
Block a user