cdb/src/db.rs

88 lines
2 KiB
Rust
Raw Normal View History

2024-06-22 00:05:22 +00:00
use crate::item::Item;
2024-05-03 16:22:59 +00:00
2024-06-22 00:05:22 +00:00
/// Collect database results into a `Vec<_>`
2024-05-03 16:22:59 +00:00
#[macro_export]
macro_rules! collect_results {
($res:expr) => {{
2024-05-10 09:59:05 +00:00
use futures::stream::TryStreamExt;
2024-05-03 16:22:59 +00:00
let mut ret = vec![];
while let Some(doc) = $res.try_next().await.unwrap() {
ret.push(doc);
}
ret
}};
}
2024-06-22 00:05:22 +00:00
/// Get a database collection
2024-05-03 16:22:59 +00:00
#[macro_export]
macro_rules! cdb_col {
($db:expr, $col:expr) => {
$db.database("cdb")
.collection::<mongodb::bson::Document>($col)
};
}
2024-06-22 00:05:22 +00:00
/// Get a MongoDB Client from the environment
2024-05-03 16:22:59 +00:00
#[macro_export]
macro_rules! get_mongo {
() => {
mongodb::Client::with_uri_str(std::env::var("DB_URI").unwrap())
.await
.unwrap()
};
}
2024-06-22 00:05:22 +00:00
/// MongoDB filter for the `_id` field.
2024-05-03 16:45:23 +00:00
#[macro_export]
macro_rules! id_of {
($id:expr) => {
doc! { "_id": $id}
};
}
2024-06-22 00:05:22 +00:00
/// Item database
2024-05-03 16:22:59 +00:00
pub struct ItemDB {
index: mdq::Index,
}
impl ItemDB {
2024-06-22 00:05:22 +00:00
/// Create a new item database using `dir` as the base.
///
/// The directory should contain markdown documents with valid frontmatter to be parsed into `Item`s
2024-05-10 08:56:07 +00:00
pub async fn new(dir: &str) -> Self {
2024-05-03 16:22:59 +00:00
// scan for markdown item entries
let index = mdq::Index::new(dir, true);
let mongodb = get_mongo!();
for item in &index.documents {
2024-06-22 00:05:22 +00:00
let item = Item::new(item);
2024-05-03 16:22:59 +00:00
item.init_db(&mongodb).await;
}
2024-05-10 08:56:07 +00:00
Self { index }
2024-05-03 16:22:59 +00:00
}
/// Retrieves an item by name
pub fn get_item(&self, item: &str) -> Option<Item> {
2024-06-22 00:05:22 +00:00
Some(
2024-05-03 16:22:59 +00:00
self.index
.documents
.iter()
2024-06-22 00:05:22 +00:00
.map(Item::new) // <-- todo : performance?
2024-05-03 16:22:59 +00:00
.find(|x| x.name == item)?,
2024-06-22 00:05:22 +00:00
)
2024-05-03 16:22:59 +00:00
}
/// Get all items
pub fn items(&self) -> Vec<String> {
let mut ret = vec![];
for item in &self.index.documents {
2024-06-22 00:05:22 +00:00
let item = Item::new(item);
2024-05-03 16:22:59 +00:00
ret.push(item.name);
}
ret
}
}