add createOrUpdate for recipes

This commit is contained in:
Anika Raemer 2025-10-10 18:04:59 +02:00
parent 7252b072bd
commit 58ef7fbc00
4 changed files with 54 additions and 0 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 { RecipeEntity } from "../entities/RecipeEntity.js";
/**
* Controls all recipe specific actions
@ -28,6 +29,37 @@ export class RecipeHandler {
const recipeDto = this.mapper.toDto(recipeEntity);
return recipeDto;
}
/**
* Save or update recipe depending on whether the DTO contains an ID
* @param dto recipe data
* @returns Recipe as saved in the database
*/
async createOrUpdateRecipe(dto: RecipeDto){
if (!this.isRecipeDtoValid(dto)) {
throw new ValidationError("recipe data is not valid!")
}
var savedEntity: RecipeEntity;
const recipeId = dto.id
if(recipeId === undefined){
// create new recipe
const recipeEntity = this.mapper.toEntity(dto)
savedEntity = await this.recipeRepository.create(recipeEntity);
throw new ValidationError("Trying to update recipe without ID!")
} else {
// save existing Recipe
// First: Load current version of recipe from database
const recipeEntity = await this.recipeRepository.findById(recipeId);
if(!recipeEntity){
throw new ValidationError("No recipe with ID " + recipeId + " found in database!")
}
// merge changes into entity
this.mapper.mergeDtoIntoEntity(dto, recipeEntity);
// persist changes
savedEntity = await this.recipeRepository.update(recipeEntity);
}
return this.mapper.toDto(savedEntity);
}
/**
* Update recipe data
* @param RecipeDto containing the entire updated recipe