app,server: Allow to display a recipe

This commit is contained in:
traxys 2023-06-25 15:13:15 +02:00
parent f3788e31a9
commit 1a0ffb2d89
5 changed files with 159 additions and 4 deletions

View file

@ -1,5 +1,10 @@
use api::{CreateRecipeRequest, CreateRecipeResponse, ListRecipesResponse};
use axum::{extract::State, Json};
use api::{
CreateRecipeRequest, CreateRecipeResponse, IngredientInfo, ListRecipesResponse, RecipeInfo,
};
use axum::{
extract::{Path, State},
Json,
};
use sea_orm::{prelude::*, ActiveValue, TransactionTrait};
use crate::entity::{ingredient, prelude::*, recipe, recipe_ingerdients, recipe_steps};
@ -77,3 +82,55 @@ pub(super) async fn list_recipes(
}
.into())
}
#[derive(serde::Deserialize)]
pub(super) struct RecipeId {
recipe_id: i64,
}
pub(super) async fn fetch_recipe(
AuthorizedHousehold(household): AuthorizedHousehold,
State(state): State<AppState>,
Path(RecipeId { recipe_id }): Path<RecipeId>,
) -> JsonResult<RecipeInfo> {
let Some(recipe) = household
.find_related(Recipe)
.filter(recipe::Column::Id.eq(recipe_id))
.one(&state.db).await? else {
return Err(RouteError::RessourceNotFound);
};
let steps = recipe
.find_related(RecipeSteps)
.all(&state.db)
.await?
.into_iter()
.map(|m| m.text)
.collect();
let recipe_ingredients = recipe.find_related(Ingredient).all(&state.db).await?;
let mut ingredients = Vec::new();
for ingredient in recipe_ingredients {
ingredients.push((
ingredient.id,
IngredientInfo {
name: ingredient.name,
unit: ingredient.unit,
},
RecipeIngerdients::find_by_id((recipe.id, ingredient.id))
.one(&state.db)
.await?
.expect("Ingredient should exist as it was fetched")
.amount,
));
}
Ok(RecipeInfo {
name: recipe.name,
steps,
ingredients,
}
.into())
}