From c77fa24515c5c98338026c88c5b6a54765ca31e4 Mon Sep 17 00:00:00 2001 From: Jeremy Wall Date: Mon, 23 Sep 2024 20:10:20 -0400 Subject: [PATCH] refactor: recipe conversion from recipe_entry --- recipes/src/lib.rs | 10 ++++++++++ web/src/app_state.rs | 17 ++++++----------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/recipes/src/lib.rs b/recipes/src/lib.rs index 7d7bc04..ac57f39 100644 --- a/recipes/src/lib.rs +++ b/recipes/src/lib.rs @@ -148,6 +148,16 @@ impl Recipe { } } +impl TryFrom<&RecipeEntry> for Recipe { + type Error = String; + + fn try_from(value: &RecipeEntry) -> Result { + let mut parsed = parse::as_recipe(&value.text)?; + parsed.serving_count = value.serving_count.clone(); + Ok(parsed) + } +} + pub struct IngredientAccumulator { inner: BTreeMap)>, } diff --git a/web/src/app_state.rs b/web/src/app_state.rs index b0febdc..679313e 100644 --- a/web/src/app_state.rs +++ b/web/src/app_state.rs @@ -151,14 +151,13 @@ pub fn parse_recipes( Some(parsed) => { let mut parsed_map = BTreeMap::new(); for r in parsed { - let mut recipe = match parse::as_recipe(&r.recipe_text()) { + let recipe = match r.try_into() { Ok(r) => r, Err(e) => { error!("Error parsing recipe {}", e); continue; } }; - recipe.serving_count = r.serving_count; parsed_map.insert(r.recipe_id().to_owned(), recipe); } Ok(Some(parsed_map)) @@ -335,20 +334,16 @@ impl MessageMapper for StateMachine { } }, Message::SaveRecipe(entry, callback) => { - let recipe = - parse::as_recipe(entry.recipe_text()).expect("Failed to parse RecipeEntry"); - original_copy - .recipes - .insert(entry.recipe_id().to_owned(), recipe); + let recipe_id = entry.recipe_id().to_owned(); + let recipe: Recipe = (&entry).try_into().expect("Failed to parse RecipeEntry"); + original_copy.recipes.insert(recipe_id.clone(), recipe); if !original_copy.recipe_counts.contains_key(entry.recipe_id()) { - original_copy - .recipe_counts - .insert(entry.recipe_id().to_owned(), 0); + original_copy.recipe_counts.insert(recipe_id.clone(), 0); } if let Some(cat) = entry.category().cloned() { original_copy .recipe_categories - .entry(entry.recipe_id().to_owned()) + .entry(recipe_id.clone()) .and_modify(|c| *c = cat.clone()) .or_insert(cat); }