This commit is contained in:
JMARyA 2024-06-22 02:05:22 +02:00
parent b8caa43972
commit 4295bdcb8d
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263
7 changed files with 109 additions and 36 deletions

View file

@ -1,5 +1,6 @@
use crate::item::{Item, ItemEntry};
use crate::item::Item;
/// Collect database results into a `Vec<_>`
#[macro_export]
macro_rules! collect_results {
($res:expr) => {{
@ -14,6 +15,7 @@ macro_rules! collect_results {
}};
}
/// Get a database collection
#[macro_export]
macro_rules! cdb_col {
($db:expr, $col:expr) => {
@ -22,6 +24,7 @@ macro_rules! cdb_col {
};
}
/// Get a MongoDB Client from the environment
#[macro_export]
macro_rules! get_mongo {
() => {
@ -31,6 +34,7 @@ macro_rules! get_mongo {
};
}
/// MongoDB filter for the `_id` field.
#[macro_export]
macro_rules! id_of {
($id:expr) => {
@ -38,18 +42,22 @@ macro_rules! id_of {
};
}
/// Item database
pub struct ItemDB {
index: mdq::Index,
}
impl ItemDB {
/// 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
pub async fn new(dir: &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);
let item = Item::new(item);
item.init_db(&mongodb).await;
}
@ -58,20 +66,20 @@ impl ItemDB {
/// Retrieves an item by name
pub fn get_item(&self, item: &str) -> Option<Item> {
Some(Item::new(
Some(
self.index
.documents
.iter()
.map(ItemEntry::new)
.map(Item::new) // <-- todo : performance?
.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);
let item = Item::new(item);
ret.push(item.name);
}
ret