feat: initial work on MongoDB support
This commit is contained in:
29
swordfish-common/src/database/katana.rs
Normal file
29
swordfish-common/src/database/katana.rs
Normal file
@ -0,0 +1,29 @@
|
||||
use mongodb::Collection;
|
||||
|
||||
use crate::database;
|
||||
use crate::structs::Card;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
static KATANA: OnceLock<Collection<Card>> = OnceLock::new();
|
||||
|
||||
///
|
||||
/// Initialize the "katana" collection in MongoDB
|
||||
///
|
||||
/// This method is called automatically when you initialize the
|
||||
/// database module.
|
||||
///
|
||||
pub fn init() {
|
||||
KATANA
|
||||
.set(
|
||||
database::MONGO_DATABASE
|
||||
.get()
|
||||
.unwrap()
|
||||
.collection::<Card>("katana"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn query_card() {
|
||||
todo!("Query card from database");
|
||||
println!("{:?}", card);
|
||||
}
|
||||
37
swordfish-common/src/database/mod.rs
Normal file
37
swordfish-common/src/database/mod.rs
Normal file
@ -0,0 +1,37 @@
|
||||
pub mod katana;
|
||||
|
||||
use mongodb::options::ClientOptions;
|
||||
use mongodb::{Client, Database};
|
||||
use std::env;
|
||||
use std::sync::OnceLock;
|
||||
use tracing::info;
|
||||
|
||||
static MONGO_CLIENT: OnceLock<Client> = OnceLock::new();
|
||||
static MONGO_DATABASE: OnceLock<Database> = OnceLock::new();
|
||||
|
||||
async fn init() {
|
||||
let mut options =
|
||||
ClientOptions::parse(env::var("MONGODB_URL").expect("MongoDB url must be provided"))
|
||||
.await
|
||||
.unwrap();
|
||||
match env::var("MONGODB_USERNAME") {
|
||||
Ok(username) => {
|
||||
options.credential = Some(
|
||||
mongodb::options::Credential::builder()
|
||||
.username(username)
|
||||
.password(
|
||||
env::var("MONGODB_PASSWORD").expect("MongoDB password must be provided"),
|
||||
)
|
||||
.build(),
|
||||
);
|
||||
}
|
||||
Err(_) => {
|
||||
info!("No MongoDB username provided, using authentication provided in the url");
|
||||
}
|
||||
}
|
||||
MONGO_CLIENT
|
||||
.set(Client::with_options(options).unwrap())
|
||||
.unwrap();
|
||||
MONGO_DATABASE.set(MONGO_CLIENT.get().unwrap().database("swordfish"));
|
||||
katana::init();
|
||||
}
|
||||
Reference in New Issue
Block a user