implement update recipe - does not create new ingredient groups, incredients or instruction steps yet

This commit is contained in:
Anika Raemer 2025-09-28 20:28:53 +02:00
parent 21742e3b24
commit e33dfdb845
3 changed files with 152 additions and 1 deletions

View file

@ -5,6 +5,7 @@ import { NotFoundError, ValidationError } from "../errors/httpErrors.js";
import { RecipeInstructionStepDto } from "../dtos/RecipeInstructionStepDto.js";
import { RecipeIngredientGroupDto } from "../dtos/RecipeIngredientGroupDto.js";
import { RecipeIngredientDto } from "../dtos/RecipeIngredientDto.js";
import { Entity } from "typeorm";
/**
* Controls all recipe specific actions
@ -15,6 +16,11 @@ export class RecipeController {
private mapper: RecipeDtoEntityMapper
) { }
/**
* Load a specific recipe
* @param id recipe id
* @returns RecipeDto for requested recipe
*/
async getRecipeById(id: string){
const recipeEntity = await this.recipeRepository.findById(id);
if(recipeEntity === null){
@ -23,6 +29,20 @@ export class RecipeController {
const recipeDto = this.mapper.toDto(recipeEntity);
return recipeDto;
}
/**
* Update recipe data
* @param RecipeDto containing the entire updated recipe
* @returns Up-to-date RecipeDto as saved in the database
*/
async updateRecipe(dto: RecipeDto){
if (!this.isRecipeDtoValid(dto)) {
throw new ValidationError("recipe data is not valid!")
}
const recipeEntity = this.mapper.toEntity(dto);
// @todo doesn't create new ingredient groups, ingredients or instruction steps yet
const savedEntity = await this.recipeRepository.save(recipeEntity);
return this.mapper.toDto(savedEntity);
}
/**
* Create a new recipe
* @param dto RecipeDto containing the new recipe

View file

@ -7,6 +7,7 @@ import { RecipeDto } from "../dtos/RecipeDto.js";
import { RecipeIngredientDtoEntityMapper } from "../mappers/RecipeIngredientDtoEntityMapper.js";
import { RecipeIngredientGroupDtoEntityMapper } from "../mappers/RecipeIngredientGroupDtoEntityMapper.js";
import { RecipeInstructionStepDtoEntityMapper } from "../mappers/RecipeInstructionStepDtoEntityMapper.js";
import { ValidationError } from "../errors/httpErrors.js";
/**
* Handles all recipe related routes
@ -40,6 +41,19 @@ router.get(
const responseDto = await recipeController.getRecipeById(id);
res.status(201).json(responseDto);
})
)
);
router.put(
"/:id",
asyncHandler(async(req, res) =>{
const id = req.params.id;
const recipeDto : RecipeDto = req.body;
if(id != recipeDto.id){
throw new ValidationError("Cannot save recipe! ID in request body " + recipeDto.id + " doesn't match ID in path " + id +"!")
}
const responseDto = await recipeController.updateRecipe(recipeDto);
res.status(201).json(responseDto);
})
);
export default router;