refactor: recipe conversion from recipe_entry

This commit is contained in:
Jeremy Wall 2024-09-23 20:10:20 -04:00
parent 6a5046d3c0
commit c77fa24515
2 changed files with 16 additions and 11 deletions

View File

@ -148,6 +148,16 @@ impl Recipe {
} }
} }
impl TryFrom<&RecipeEntry> for Recipe {
type Error = String;
fn try_from(value: &RecipeEntry) -> Result<Self, Self::Error> {
let mut parsed = parse::as_recipe(&value.text)?;
parsed.serving_count = value.serving_count.clone();
Ok(parsed)
}
}
pub struct IngredientAccumulator { pub struct IngredientAccumulator {
inner: BTreeMap<IngredientKey, (Ingredient, BTreeSet<String>)>, inner: BTreeMap<IngredientKey, (Ingredient, BTreeSet<String>)>,
} }

View File

@ -151,14 +151,13 @@ pub fn parse_recipes(
Some(parsed) => { Some(parsed) => {
let mut parsed_map = BTreeMap::new(); let mut parsed_map = BTreeMap::new();
for r in parsed { for r in parsed {
let mut recipe = match parse::as_recipe(&r.recipe_text()) { let recipe = match r.try_into() {
Ok(r) => r, Ok(r) => r,
Err(e) => { Err(e) => {
error!("Error parsing recipe {}", e); error!("Error parsing recipe {}", e);
continue; continue;
} }
}; };
recipe.serving_count = r.serving_count;
parsed_map.insert(r.recipe_id().to_owned(), recipe); parsed_map.insert(r.recipe_id().to_owned(), recipe);
} }
Ok(Some(parsed_map)) Ok(Some(parsed_map))
@ -335,20 +334,16 @@ impl MessageMapper<Message, AppState> for StateMachine {
} }
}, },
Message::SaveRecipe(entry, callback) => { Message::SaveRecipe(entry, callback) => {
let recipe = let recipe_id = entry.recipe_id().to_owned();
parse::as_recipe(entry.recipe_text()).expect("Failed to parse RecipeEntry"); let recipe: Recipe = (&entry).try_into().expect("Failed to parse RecipeEntry");
original_copy original_copy.recipes.insert(recipe_id.clone(), recipe);
.recipes
.insert(entry.recipe_id().to_owned(), recipe);
if !original_copy.recipe_counts.contains_key(entry.recipe_id()) { if !original_copy.recipe_counts.contains_key(entry.recipe_id()) {
original_copy original_copy.recipe_counts.insert(recipe_id.clone(), 0);
.recipe_counts
.insert(entry.recipe_id().to_owned(), 0);
} }
if let Some(cat) = entry.category().cloned() { if let Some(cat) = entry.category().cloned() {
original_copy original_copy
.recipe_categories .recipe_categories
.entry(entry.recipe_id().to_owned()) .entry(recipe_id.clone())
.and_modify(|c| *c = cat.clone()) .and_modify(|c| *c = cat.clone())
.or_insert(cat); .or_insert(cat);
} }