fix: check for db connection first
This commit is contained in:
@ -1,17 +1,17 @@
|
||||
use mongodb::Collection;
|
||||
|
||||
use crate::database;
|
||||
use crate::structs::Card;
|
||||
use mongodb::Collection;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
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(
|
||||
@ -25,11 +25,54 @@ pub fn init() {
|
||||
|
||||
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()
|
||||
KATANA
|
||||
.get()
|
||||
.unwrap()
|
||||
.find_one(
|
||||
mongodb::bson::doc! {
|
||||
"name": name,
|
||||
"series": series
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub async fn write_card(mut card: Card) {
|
||||
// todo!("Write card to database");
|
||||
let old_card = KATANA
|
||||
.get()
|
||||
.unwrap()
|
||||
.find_one(
|
||||
mongodb::bson::doc! {
|
||||
"name": card.name.clone(),
|
||||
"series": card.series.clone()
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let start = SystemTime::now();
|
||||
let current_time_ts = start
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("Time went backwards");
|
||||
card.last_update_ts = current_time_ts.as_secs() as i64;
|
||||
if old_card.is_some() {
|
||||
KATANA
|
||||
.get()
|
||||
.unwrap()
|
||||
.replace_one(
|
||||
mongodb::bson::doc! {
|
||||
"name": card.name.clone(),
|
||||
"series": card.series.clone()
|
||||
},
|
||||
card,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
} else {
|
||||
KATANA.get().unwrap().insert_one(card, None).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@ -35,10 +35,10 @@ pub async fn init() {
|
||||
}
|
||||
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");
|
||||
db.run_command(doc! { "ping": 1 }, None)
|
||||
.await
|
||||
.expect("Failed to connect to MongoDB");
|
||||
MONGO_DATABASE.set(db).unwrap();
|
||||
MONGO_CLIENT
|
||||
.set(client)
|
||||
.unwrap();
|
||||
MONGO_CLIENT.set(client).unwrap();
|
||||
katana::init();
|
||||
}
|
||||
|
||||
@ -6,4 +6,5 @@ pub struct Card {
|
||||
pub name: String,
|
||||
pub series: String,
|
||||
pub print: i32,
|
||||
pub last_update_ts: i64,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user