feat(common): implement database reading

Also fix some bugs
This commit is contained in:
2024-01-06 14:34:45 +07:00
parent 30a7098bed
commit dbc168a955
7 changed files with 77 additions and 35 deletions

View File

@ -9,6 +9,7 @@ edition = "2021"
leptess = "0.14.0"
log = "0.4.20"
rusty-tesseract = "1.1.9"
serde = "1.0.195"
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }

View File

@ -23,7 +23,13 @@ pub fn init() {
.unwrap();
}
fn query_card() {
todo!("Query card from database");
println!("{:?}", card);
pub async fn query_card(name: &str, series: &str) -> Option<Card> {
// todo!("Query card from database");
KATANA.get().unwrap().find_one(
mongodb::bson::doc! {
"name": name,
"series": series
},
None,
).await.unwrap()
}

View File

@ -1,5 +1,6 @@
pub mod katana;
use mongodb::bson::doc;
use mongodb::options::ClientOptions;
use mongodb::{Client, Database};
use std::env;
@ -9,11 +10,14 @@ use tracing::info;
static MONGO_CLIENT: OnceLock<Client> = OnceLock::new();
static MONGO_DATABASE: OnceLock<Database> = OnceLock::new();
async fn init() {
pub async fn init() {
let mut options =
ClientOptions::parse(env::var("MONGODB_URL").expect("MongoDB url must be provided"))
.await
.unwrap();
options.direct_connection = Some(true);
options.app_name = Some("swordfish".to_string());
options.default_database = Some("swordfish".to_string());
match env::var("MONGODB_USERNAME") {
Ok(username) => {
options.credential = Some(
@ -29,9 +33,12 @@ async fn init() {
info!("No MongoDB username provided, using authentication provided in the url");
}
}
let client = Client::with_options(options).unwrap();
let db = client.database("swordfish");
db.run_command(doc! { "ping": 1 }, None).await.expect("Failed to connect to MongoDB");
MONGO_DATABASE.set(db).unwrap();
MONGO_CLIENT
.set(Client::with_options(options).unwrap())
.set(client)
.unwrap();
MONGO_DATABASE.set(MONGO_CLIENT.get().unwrap().database("swordfish"));
katana::init();
}

View File

@ -1,4 +1,6 @@
#[derive(Debug)]
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Card {
pub wishlist: Option<i32>,
pub name: String,