This commit is contained in:
JMARyA 2024-05-03 18:22:59 +02:00
parent 897d23f917
commit c752e09f1a
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263
7 changed files with 380 additions and 363 deletions

73
src/db.rs Normal file
View file

@ -0,0 +1,73 @@
use crate::item::{Item, ItemEntry};
#[macro_export]
macro_rules! collect_results {
($res:expr) => {{
let mut ret = vec![];
while let Some(doc) = $res.try_next().await.unwrap() {
ret.push(doc);
}
ret
}};
}
#[macro_export]
macro_rules! cdb_col {
($db:expr, $col:expr) => {
$db.database("cdb")
.collection::<mongodb::bson::Document>($col)
};
}
#[macro_export]
macro_rules! get_mongo {
() => {
mongodb::Client::with_uri_str(std::env::var("DB_URI").unwrap())
.await
.unwrap()
};
}
pub struct ItemDB {
index: mdq::Index,
mongodb: mongodb::Client,
}
impl ItemDB {
pub async fn new(dir: &str, mongodb: &str) -> Self {
// scan for markdown item entries
let index = mdq::Index::new(dir, true);
let mongodb = get_mongo!();
for item in &index.documents {
let item = ItemEntry::new(item.clone());
item.init_db(&mongodb).await;
}
Self { index, mongodb }
}
/// Retrieves an item by name
pub fn get_item(&self, item: &str) -> Option<Item> {
Some(Item::new(
self.mongodb.clone(),
self.index
.documents
.iter()
.map(|x| ItemEntry::new(x.clone()))
.find(|x| x.name == item)?,
))
}
/// Get all items
pub fn items(&self) -> Vec<String> {
let mut ret = vec![];
for item in &self.index.documents {
let item = ItemEntry::new(item.clone());
ret.push(item.name);
}
ret
}
}