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:
parent
0a9251df67
commit
f62e836692
2 changed files with 13 additions and 3 deletions
|
|
@ -83,7 +83,7 @@ public class Recipe {
|
|||
private List<String> preparationSteps = new ArrayList<>();
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
private Recipe() {
|
||||
public Recipe() {
|
||||
// for object mapper
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package server.api;
|
|||
|
||||
import commons.Recipe;
|
||||
|
||||
import org.springframework.data.domain.Example;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
|
|
@ -86,11 +87,20 @@ public class RecipeController {
|
|||
* Inserts a new recipe into the repository
|
||||
* </p>
|
||||
* @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")
|
||||
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();
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue