fix: createRecipe checks name is unique

Uses JPA Repository.exists(Example<T>); Changed no-arg constuctor of
Recipe to public.
This commit is contained in:
Zhongheng Liu 2025-11-22 01:16:38 +01:00
commit f62e836692
2 changed files with 13 additions and 3 deletions

View file

@ -83,7 +83,7 @@ public class Recipe {
private List<String> preparationSteps = new ArrayList<>(); private List<String> preparationSteps = new ArrayList<>();
@SuppressWarnings("unused") @SuppressWarnings("unused")
private Recipe() { public Recipe() {
// for object mapper // for object mapper
} }

View file

@ -2,6 +2,7 @@ package server.api;
import commons.Recipe; import commons.Recipe;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -86,11 +87,20 @@ public class RecipeController {
* Inserts a new recipe into the repository * Inserts a new recipe into the repository
* </p> * </p>
* @param recipe The new recipe as a request body * @param recipe The new recipe as a request body
* @return 200 OK with the recipe you added; or 400 Bad Request if the recipe already exists * @return 200 OK with the recipe you added; or 400 Bad Request if the recipe already exists by name
*/ */
@PutMapping("/recipe/new") @PutMapping("/recipe/new")
public ResponseEntity<Recipe> createRecipe(@RequestBody Recipe recipe) { public ResponseEntity<Recipe> createRecipe(@RequestBody Recipe recipe) {
if (recipeRepository.existsById(recipe.getId())) {
// We initialize a new example recipe with the name of input recipe
// This is the only attribute we are concerned about making sure it's unique
Recipe example = new Recipe();
example.setName(recipe.getName());
/* Here we use very funny JPA magic repository.exists(Example<Recipe>)
We check if any recipe in the repository has the same name as the input
*/
if (recipeRepository.exists(Example.of(example))) {
return ResponseEntity.badRequest().build(); return ResponseEntity.badRequest().build();
} }