From ac84468d7bf3fd31e478cbe21f68023c78a03040 Mon Sep 17 00:00:00 2001 From: Lesly Villanueva Date: Mon, 19 Oct 2026 20:17:57 -0700 Subject: [PATCH 1/6] added recipe request and response records --- .../csumb/cst438/api/record/RecipeCreate.java | 19 ++++++++++++ .../csumb/cst438/api/record/RecipePatch.java | 17 +++++++++++ .../cst438/api/record/RecipeResponse.java | 30 +++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 api/src/main/java/edu/csumb/cst438/api/record/RecipeCreate.java create mode 100644 api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java create mode 100644 api/src/main/java/edu/csumb/cst438/api/record/RecipeResponse.java diff --git a/api/src/main/java/edu/csumb/cst438/api/record/RecipeCreate.java b/api/src/main/java/edu/csumb/cst438/api/record/RecipeCreate.java new file mode 100644 index 0000000..da7cd2a --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/RecipeCreate.java @@ -0,0 +1,19 @@ +package edu.csumb.cst438.api.record; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +import java.util.Set; + +public record RecipeCreate( + @NotBlank(message = "Recipe name is required") + String name, + + @NotNull(message = "Ingredient IDs are required") + Set ingredientIds, + + String measurements, + + String instructions +) { +} \ No newline at end of file diff --git a/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java b/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java new file mode 100644 index 0000000..b3efae9 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java @@ -0,0 +1,17 @@ +package edu.csumb.cst438.api.record; + +import jakarta.validation.constraints.Size; + +import java.util.Set; + +public record RecipePatch( + @Size(min = 1, message = "Name must not be blank") + String name, + + Set ingredientIds, + + String measurements, + + String instructions +) { +} \ No newline at end of file diff --git a/api/src/main/java/edu/csumb/cst438/api/record/RecipeResponse.java b/api/src/main/java/edu/csumb/cst438/api/record/RecipeResponse.java new file mode 100644 index 0000000..6a64ba8 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/RecipeResponse.java @@ -0,0 +1,30 @@ +package edu.csumb.cst438.api.record; + +import edu.csumb.cst438.api.entity.Recipe; + +import java.time.Instant; +import java.util.Set; +import java.util.stream.Collectors; + +public record RecipeResponse( + Long id, + String name, + Instant createdAt, + Set ingredients, + String measurements, + String instructions +) { + public static RecipeResponse from(Recipe recipe) { + return new RecipeResponse( + recipe.getId(), + recipe.getName(), + recipe.getCreatedAt(), + recipe.getIngredients() + .stream() + .map(IngredientResponse::from) + .collect(Collectors.toSet()), + recipe.getMeasurements(), + recipe.getInstructions() + ); + } +} \ No newline at end of file From 8487bef0bcf6639aaa805ad42a52aacfa6cd5cb7 Mon Sep 17 00:00:00 2001 From: Lesly Villanueva Date: Mon, 19 Oct 2026 20:18:59 -0700 Subject: [PATCH 2/6] add recipe repository --- .../csumb/cst438/api/repository/RecipeRepository.java | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 api/src/main/java/edu/csumb/cst438/api/repository/RecipeRepository.java diff --git a/api/src/main/java/edu/csumb/cst438/api/repository/RecipeRepository.java b/api/src/main/java/edu/csumb/cst438/api/repository/RecipeRepository.java new file mode 100644 index 0000000..f6775f1 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/repository/RecipeRepository.java @@ -0,0 +1,10 @@ +package edu.csumb.cst438.api.repository; + +import edu.csumb.cst438.api.entity.Recipe; +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * Repository for accessing recipes in the database. + */ +public interface RecipeRepository extends JpaRepository { +} \ No newline at end of file From f6692817a0b25f7de290b634dd4b29fc6a33bec5 Mon Sep 17 00:00:00 2001 From: Lesly Villanueva Date: Mon, 19 Oct 2026 21:59:09 -0700 Subject: [PATCH 3/6] implement recipe service and controller --- .../api/controller/RecipeController.java | 163 ++++++++++++++++++ .../cst438/api/service/RecipeService.java | 160 +++++++++++++++++ 2 files changed, 323 insertions(+) create mode 100644 api/src/main/java/edu/csumb/cst438/api/controller/RecipeController.java create mode 100644 api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java diff --git a/api/src/main/java/edu/csumb/cst438/api/controller/RecipeController.java b/api/src/main/java/edu/csumb/cst438/api/controller/RecipeController.java new file mode 100644 index 0000000..6ac4b23 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/controller/RecipeController.java @@ -0,0 +1,163 @@ +package edu.csumb.cst438.api.controller; + +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.RecipeCreate; +import edu.csumb.cst438.api.record.RecipePatch; +import edu.csumb.cst438.api.record.RecipeResponse; +import edu.csumb.cst438.api.repository.UserRepository; +import edu.csumb.cst438.api.service.RecipeService; +import jakarta.validation.Valid; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PagedModel; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; + +@RestController +@RequestMapping("/api/v1/recipes") +public class RecipeController { + + private final RecipeService recipeService; + private final UserRepository userRepository; + + public RecipeController( + RecipeService recipeService, + UserRepository userRepository) { + this.recipeService = recipeService; + this.userRepository = userRepository; + } + + @GetMapping + public PagedModel listRecipes( + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size, + @RequestParam(defaultValue = "createdAt,desc") String sort) { + + if (page < 0) { + throw new IllegalArgumentException( + "Page index must be 0 or greater"); + } + + if (size < 1 || size > 100) { + throw new IllegalArgumentException( + "Page size must be between 1 and 100"); + } + + Pageable pageable = createPageable(page, size, sort); + + return new PagedModel<>( + recipeService.listRecipes(pageable) + ); + } + + @PostMapping + public ResponseEntity createRecipe( + @Valid @RequestBody RecipeCreate request, + Authentication authentication) { + + User owner = getCurrentUser(authentication); + + RecipeResponse created = + recipeService.createRecipe(request, owner); + + return ResponseEntity + .created(URI.create( + "/api/v1/recipes/" + created.id() + )) + .body(created); + } + + @GetMapping("/{recipeId}") + public RecipeResponse getRecipe(@PathVariable Long recipeId) { + return recipeService.getRecipe(recipeId); + } + + @PutMapping("/{recipeId}") + public RecipeResponse replaceRecipe( + @PathVariable Long recipeId, + @Valid @RequestBody RecipeCreate request, + Authentication authentication) { + + User owner = getCurrentUser(authentication); + + return recipeService.replaceRecipe( + recipeId, + request, + owner + ); + } + + @PatchMapping("/{recipeId}") + public RecipeResponse patchRecipe( + @PathVariable Long recipeId, + @Valid @RequestBody RecipePatch request, + Authentication authentication) { + + User owner = getCurrentUser(authentication); + + return recipeService.patchRecipe( + recipeId, + request, + owner + ); + } + + @DeleteMapping("/{recipeId}") + public ResponseEntity deleteRecipe( + @PathVariable Long recipeId, + Authentication authentication) { + + User owner = getCurrentUser(authentication); + + recipeService.deleteRecipe(recipeId, owner); + + return ResponseEntity.noContent().build(); + } + + private User getCurrentUser(Authentication authentication) { + return userRepository.findByEmail(authentication.getName()) + .orElseThrow(() -> new IllegalArgumentException( + "Authenticated user was not found")); + } + + private Pageable createPageable( + int page, + int size, + String sort) { + + String[] sortParts = sort.split(","); + + if (sortParts.length != 2) { + throw new IllegalArgumentException( + "Sort must use the format field,direction"); + } + + String field = sortParts[0]; + String direction = sortParts[1]; + + if (!field.equals("name") && !field.equals("createdAt")) { + throw new IllegalArgumentException( + "Recipes can only be sorted by name or createdAt"); + } + + if (!direction.equals("asc") && !direction.equals("desc")) { + throw new IllegalArgumentException( + "Sort direction must be asc or desc"); + } + + Sort.Direction sortDirection = + direction.equals("asc") + ? Sort.Direction.ASC + : Sort.Direction.DESC; + + return PageRequest.of( + page, + size, + Sort.by(sortDirection, field) + ); + } +} \ No newline at end of file diff --git a/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java b/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java new file mode 100644 index 0000000..ca8f699 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java @@ -0,0 +1,160 @@ +package edu.csumb.cst438.api.service; + +import edu.csumb.cst438.api.entity.Ingredient; +import edu.csumb.cst438.api.entity.Recipe; +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.RecipeCreate; +import edu.csumb.cst438.api.record.RecipePatch; +import edu.csumb.cst438.api.record.RecipeResponse; +import edu.csumb.cst438.api.repository.IngredientRepository; +import edu.csumb.cst438.api.repository.RecipeRepository; +import jakarta.persistence.EntityNotFoundException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Service +@Transactional +public class RecipeService { + + private final RecipeRepository recipeRepository; + private final IngredientRepository ingredientRepository; + + public RecipeService( + RecipeRepository recipeRepository, + IngredientRepository ingredientRepository) { + this.recipeRepository = recipeRepository; + this.ingredientRepository = ingredientRepository; + } + + @Transactional(readOnly = true) + public Page listRecipes(Pageable pageable) { + return recipeRepository + .findAll(pageable) + .map(RecipeResponse::from); + } + + public RecipeResponse createRecipe( + RecipeCreate request, + User owner) { + + Set ingredients = + findIngredients(request.ingredientIds()); + + Recipe recipe = new Recipe( + request.name(), + request.measurements(), + request.instructions(), + owner + ); + + ingredients.forEach(recipe::addIngredient); + + return RecipeResponse.from(recipeRepository.save(recipe)); + } + + @Transactional(readOnly = true) + public RecipeResponse getRecipe(Long recipeId) { + Recipe recipe = recipeRepository.findById(recipeId) + .orElseThrow(() -> new EntityNotFoundException( + "Recipe " + recipeId + " not found")); + + return RecipeResponse.from(recipe); + } + + public RecipeResponse replaceRecipe( + Long recipeId, + RecipeCreate request, + User owner) { + + Recipe recipe = findOwnedRecipe(recipeId, owner); + + recipe.updateDetails( + request.name(), + request.measurements(), + request.instructions() + ); + + replaceIngredients(recipe, request.ingredientIds()); + + return RecipeResponse.from(recipe); + } + + public RecipeResponse patchRecipe( + Long recipeId, + RecipePatch request, + User owner) { + + Recipe recipe = findOwnedRecipe(recipeId, owner); + + String name = request.name() != null + ? request.name() + : recipe.getName(); + + String measurements = request.measurements() != null + ? request.measurements() + : recipe.getMeasurements(); + + String instructions = request.instructions() != null + ? request.instructions() + : recipe.getInstructions(); + + recipe.updateDetails(name, measurements, instructions); + + if (request.ingredientIds() != null) { + replaceIngredients(recipe, request.ingredientIds()); + } + + return RecipeResponse.from(recipe); + } + + public void deleteRecipe(Long recipeId, User owner) { + Recipe recipe = findOwnedRecipe(recipeId, owner); + recipeRepository.delete(recipe); + } + + private Recipe findOwnedRecipe(Long recipeId, User owner) { + Recipe recipe = recipeRepository.findById(recipeId) + .orElseThrow(() -> new EntityNotFoundException( + "Recipe " + recipeId + " not found")); + + if (recipe.getOwner() == null + || !recipe.getOwner().getId().equals(owner.getId())) { + throw new EntityNotFoundException( + "Recipe " + recipeId + " not found"); + } + + return recipe; + } + + private void replaceIngredients( + Recipe recipe, + Set ingredientIds) { + + Set newIngredients = + findIngredients(ingredientIds); + + Set oldIngredients = + new HashSet<>(recipe.getIngredients()); + + oldIngredients.forEach(recipe::removeIngredient); + newIngredients.forEach(recipe::addIngredient); + } + + private Set findIngredients(Set ingredientIds) { + List ingredients = + ingredientRepository.findAllById(ingredientIds); + + if (ingredients.size() != ingredientIds.size()) { + throw new EntityNotFoundException( + "One or more ingredients were not found"); + } + + return new HashSet<>(ingredients); + } +} \ No newline at end of file From a49bb48a0f534fd882892812a71b570083ec1359 Mon Sep 17 00:00:00 2001 From: Lesly Villanueva Date: Tue, 20 Oct 2026 15:47:31 -0700 Subject: [PATCH 4/6] Add recipe service test and validation fixes --- .../csumb/cst438/api/record/RecipePatch.java | 12 +- .../cst438/api/service/RecipeService.java | 143 ++++++- .../cst438/api/service/RecipeServiceTest.java | 352 ++++++++++++++++++ 3 files changed, 491 insertions(+), 16 deletions(-) create mode 100644 api/src/test/java/edu/csumb/cst438/api/service/RecipeServiceTest.java diff --git a/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java b/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java index b3efae9..9d86bc8 100644 --- a/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java +++ b/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java @@ -1,17 +1,21 @@ package edu.csumb.cst438.api.record; -import jakarta.validation.constraints.Size; +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.validation.constraints.Pattern; import java.util.Set; public record RecipePatch( - @Size(min = 1, message = "Name must not be blank") + @Pattern( + regexp = ".*\\S.*", + message = "Name must not be blank" + ) String name, Set ingredientIds, - String measurements, + JsonNode measurements, - String instructions + JsonNode instructions ) { } \ No newline at end of file diff --git a/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java b/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java index ca8f699..497dee3 100644 --- a/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java +++ b/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java @@ -1,5 +1,6 @@ package edu.csumb.cst438.api.service; +import com.fasterxml.jackson.databind.JsonNode; import edu.csumb.cst438.api.entity.Ingredient; import edu.csumb.cst438.api.entity.Recipe; import edu.csumb.cst438.api.entity.User; @@ -18,6 +19,9 @@ import java.util.List; import java.util.Set; +/** + * Provides business logic for recipe operations. + */ @Service @Transactional public class RecipeService { @@ -25,6 +29,12 @@ public class RecipeService { private final RecipeRepository recipeRepository; private final IngredientRepository ingredientRepository; + /** + * Creates a recipe service. + * + * @param recipeRepository repository for recipes + * @param ingredientRepository repository for ingredients + */ public RecipeService( RecipeRepository recipeRepository, IngredientRepository ingredientRepository) { @@ -32,6 +42,12 @@ public RecipeService( this.ingredientRepository = ingredientRepository; } + /** + * Lists recipes using pagination and sorting. + * + * @param pageable pagination and sorting information + * @return a page of recipes + */ @Transactional(readOnly = true) public Page listRecipes(Pageable pageable) { return recipeRepository @@ -39,6 +55,13 @@ public Page listRecipes(Pageable pageable) { .map(RecipeResponse::from); } + /** + * Creates a recipe for the specified user. + * + * @param request recipe creation data + * @param owner user who owns the recipe + * @return the created recipe + */ public RecipeResponse createRecipe( RecipeCreate request, User owner) { @@ -55,18 +78,36 @@ public RecipeResponse createRecipe( ingredients.forEach(recipe::addIngredient); - return RecipeResponse.from(recipeRepository.save(recipe)); + return RecipeResponse.from( + recipeRepository.save(recipe) + ); } + /** + * Retrieves a recipe by ID. + * + * @param recipeId recipe ID + * @return the requested recipe + * @throws EntityNotFoundException if the recipe does not exist + */ @Transactional(readOnly = true) public RecipeResponse getRecipe(Long recipeId) { Recipe recipe = recipeRepository.findById(recipeId) .orElseThrow(() -> new EntityNotFoundException( - "Recipe " + recipeId + " not found")); + "Recipe " + recipeId + " not found" + )); return RecipeResponse.from(recipe); } + /** + * Replaces all editable fields of a user's recipe. + * + * @param recipeId recipe ID + * @param request replacement data + * @param owner authenticated user + * @return the updated recipe + */ public RecipeResponse replaceRecipe( Long recipeId, RecipeCreate request, @@ -85,6 +126,17 @@ public RecipeResponse replaceRecipe( return RecipeResponse.from(recipe); } + /** + * Partially updates a user's recipe. + * + * Missing fields retain their existing values. Fields explicitly set + * to null are cleared. + * + * @param recipeId recipe ID + * @param request partial update data + * @param owner authenticated user + * @return the updated recipe + */ public RecipeResponse patchRecipe( Long recipeId, RecipePatch request, @@ -96,15 +148,21 @@ public RecipeResponse patchRecipe( ? request.name() : recipe.getName(); - String measurements = request.measurements() != null - ? request.measurements() - : recipe.getMeasurements(); + String measurements = patchValue( + request.measurements(), + recipe.getMeasurements() + ); - String instructions = request.instructions() != null - ? request.instructions() - : recipe.getInstructions(); + String instructions = patchValue( + request.instructions(), + recipe.getInstructions() + ); - recipe.updateDetails(name, measurements, instructions); + recipe.updateDetails( + name, + measurements, + instructions + ); if (request.ingredientIds() != null) { replaceIngredients(recipe, request.ingredientIds()); @@ -113,25 +171,48 @@ public RecipeResponse patchRecipe( return RecipeResponse.from(recipe); } + /** + * Deletes a user's recipe. + * + * @param recipeId recipe ID + * @param owner authenticated user + */ public void deleteRecipe(Long recipeId, User owner) { Recipe recipe = findOwnedRecipe(recipeId, owner); recipeRepository.delete(recipe); } + /** + * Finds a recipe and verifies that it belongs to the specified user. + * + * @param recipeId recipe ID + * @param owner authenticated user + * @return the owned recipe + * @throws EntityNotFoundException if the recipe does not exist or + * belongs to another user + */ private Recipe findOwnedRecipe(Long recipeId, User owner) { Recipe recipe = recipeRepository.findById(recipeId) .orElseThrow(() -> new EntityNotFoundException( - "Recipe " + recipeId + " not found")); + "Recipe " + recipeId + " not found" + )); if (recipe.getOwner() == null || !recipe.getOwner().getId().equals(owner.getId())) { throw new EntityNotFoundException( - "Recipe " + recipeId + " not found"); + "Recipe " + recipeId + " not found" + ); } return recipe; } + /** + * Replaces all ingredients assigned to a recipe. + * + * @param recipe recipe being updated + * @param ingredientIds new ingredient IDs + */ private void replaceIngredients( Recipe recipe, Set ingredientIds) { @@ -146,15 +227,53 @@ private void replaceIngredients( newIngredients.forEach(recipe::addIngredient); } + /** + * Finds all ingredients referenced by their IDs. + * + * @param ingredientIds ingredient IDs + * @return matching ingredients + * @throws EntityNotFoundException if an ingredient is missing + */ private Set findIngredients(Set ingredientIds) { List ingredients = ingredientRepository.findAllById(ingredientIds); if (ingredients.size() != ingredientIds.size()) { throw new EntityNotFoundException( - "One or more ingredients were not found"); + "One or more ingredients were not found" + ); } return new HashSet<>(ingredients); } + + /** + * Applies PATCH semantics to a nullable text field. + * + * @param value incoming JSON value + * @param currentValue existing database value + * @return the updated value + */ + private String patchValue( + JsonNode value, + String currentValue) { + + // The field was omitted, so preserve the old value. + if (value == null) { + return currentValue; + } + + // The field was explicitly set to null, so clear it. + if (value.isNull()) { + return null; + } + + if (!value.isTextual()) { + throw new IllegalArgumentException( + "Recipe text fields must be strings or null" + ); + } + + return value.asText(); + } } \ No newline at end of file diff --git a/api/src/test/java/edu/csumb/cst438/api/service/RecipeServiceTest.java b/api/src/test/java/edu/csumb/cst438/api/service/RecipeServiceTest.java new file mode 100644 index 0000000..fdbc6d7 --- /dev/null +++ b/api/src/test/java/edu/csumb/cst438/api/service/RecipeServiceTest.java @@ -0,0 +1,352 @@ +package edu.csumb.cst438.api.service; + +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import edu.csumb.cst438.api.entity.Ingredient; +import edu.csumb.cst438.api.entity.Recipe; +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.RecipeCreate; +import edu.csumb.cst438.api.record.RecipePatch; +import edu.csumb.cst438.api.record.RecipeResponse; +import edu.csumb.cst438.api.repository.IngredientRepository; +import edu.csumb.cst438.api.repository.RecipeRepository; +import jakarta.persistence.EntityNotFoundException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; + +import java.lang.reflect.Field; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class RecipeServiceTest { + + private RecipeRepository recipeRepository; + private IngredientRepository ingredientRepository; + private RecipeService recipeService; + + private User owner; + private User otherUser; + private Ingredient flour; + private Ingredient sugar; + private Recipe recipe; + + @BeforeEach + void setUp() throws Exception { + recipeRepository = mock(RecipeRepository.class); + ingredientRepository = mock(IngredientRepository.class); + + recipeService = new RecipeService( + recipeRepository, + ingredientRepository + ); + + owner = new User( + "owner@example.com", + "Owner", + "USER" + ); + + otherUser = new User( + "other@example.com", + "Other User", + "USER" + ); + + setId(owner, 1L); + setId(otherUser, 2L); + + flour = new Ingredient("Flour"); + sugar = new Ingredient("Sugar"); + + setId(flour, 1L); + setId(sugar, 2L); + + recipe = new Recipe( + "Pancakes", + "2 cups", + "Mix and cook.", + owner + ); + + recipe.addIngredient(flour); + setId(recipe, 10L); + } + + @Test + void listRecipesReturnsRecipes() { + Pageable pageable = PageRequest.of(0, 20); + + Page recipePage = + new PageImpl<>(List.of(recipe)); + + when(recipeRepository.findAll(pageable)) + .thenReturn(recipePage); + + Page result = + recipeService.listRecipes(pageable); + + assertEquals(1, result.getTotalElements()); + assertEquals("Pancakes", result.getContent().get(0).name()); + + verify(recipeRepository).findAll(pageable); + } + + @Test + void getRecipeReturnsRecipe() { + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + RecipeResponse result = + recipeService.getRecipe(10L); + + assertEquals(10L, result.id()); + assertEquals("Pancakes", result.name()); + } + + @Test + void getRecipeThrowsWhenRecipeDoesNotExist() { + when(recipeRepository.findById(999L)) + .thenReturn(Optional.empty()); + + assertThrows( + EntityNotFoundException.class, + () -> recipeService.getRecipe(999L) + ); + } + + @Test + void createRecipeSavesRecipeWithIngredients() { + RecipeCreate request = new RecipeCreate( + "Sugar Pancakes", + Set.of(1L, 2L), + "3 cups", + "Mix and cook." + ); + + when(ingredientRepository.findAllById(Set.of(1L, 2L))) + .thenReturn(List.of(flour, sugar)); + + when(recipeRepository.save(any(Recipe.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + RecipeResponse result = + recipeService.createRecipe(request, owner); + + assertEquals("Sugar Pancakes", result.name()); + assertEquals(2, result.ingredients().size()); + + verify(ingredientRepository) + .findAllById(Set.of(1L, 2L)); + + verify(recipeRepository).save(any(Recipe.class)); + } + + @Test + void createRecipeThrowsWhenIngredientIsMissing() { + RecipeCreate request = new RecipeCreate( + "Invalid Recipe", + Set.of(1L, 999L), + "2 cups", + "Instructions" + ); + + when(ingredientRepository.findAllById(Set.of(1L, 999L))) + .thenReturn(List.of(flour)); + + assertThrows( + EntityNotFoundException.class, + () -> recipeService.createRecipe(request, owner) + ); + + verify(recipeRepository, never()) + .save(any(Recipe.class)); + } + + @Test + void replaceRecipeUpdatesAllRecipeFields() { + RecipeCreate request = new RecipeCreate( + "Updated Pancakes", + Set.of(2L), + "4 cups", + "Updated instructions." + ); + + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + when(ingredientRepository.findAllById(Set.of(2L))) + .thenReturn(List.of(sugar)); + + RecipeResponse result = + recipeService.replaceRecipe( + 10L, + request, + owner + ); + + assertEquals("Updated Pancakes", result.name()); + assertEquals("4 cups", result.measurements()); + assertEquals( + "Updated instructions.", + result.instructions() + ); + assertEquals(1, result.ingredients().size()); + } + + @Test + void patchRecipeUpdatesOnlyProvidedFields() { + RecipePatch request = new RecipePatch( + null, + null, + null, + JsonNodeFactory.instance.textNode( + "Updated instructions." + ) + ); + + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + RecipeResponse result = + recipeService.patchRecipe( + 10L, + request, + owner + ); + + assertEquals("Pancakes", result.name()); + assertEquals("2 cups", result.measurements()); + assertEquals( + "Updated instructions.", + result.instructions() + ); + } + + @Test + void patchRecipeClearsInstructionsWhenExplicitlyNull() { + RecipePatch request = new RecipePatch( + null, + null, + null, + JsonNodeFactory.instance.nullNode() + ); + + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + RecipeResponse result = + recipeService.patchRecipe( + 10L, + request, + owner + ); + + assertNull(result.instructions()); + assertEquals("2 cups", result.measurements()); + } + + @Test + void patchRecipeReplacesIngredientsWhenIngredientIdsProvided() { + RecipePatch request = new RecipePatch( + null, + Set.of(2L), + null, + null + ); + + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + when(ingredientRepository.findAllById(Set.of(2L))) + .thenReturn(List.of(sugar)); + + RecipeResponse result = + recipeService.patchRecipe( + 10L, + request, + owner + ); + + assertEquals(1, result.ingredients().size()); + assertEquals( + "Sugar", + result.ingredients() + .iterator() + .next() + .ingredientName() + ); + } + + @Test + void deleteRecipeDeletesOwnedRecipe() { + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + recipeService.deleteRecipe(10L, owner); + + verify(recipeRepository).delete(recipe); + } + + @Test + void anotherUserCannotUpdateRecipe() { + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + RecipeCreate request = new RecipeCreate( + "Unauthorized Update", + Set.of(1L), + "1 cup", + "Instructions" + ); + + assertThrows( + EntityNotFoundException.class, + () -> recipeService.replaceRecipe( + 10L, + request, + otherUser + ) + ); + + verify(recipeRepository, never()) + .save(any(Recipe.class)); + } + + @Test + void anotherUserCannotDeleteRecipe() { + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + assertThrows( + EntityNotFoundException.class, + () -> recipeService.deleteRecipe( + 10L, + otherUser + ) + ); + + verify(recipeRepository, never()) + .delete(any(Recipe.class)); + } + + private static void setId( + Object entity, + Long id) throws Exception { + + Field idField = + entity.getClass().getDeclaredField("id"); + + idField.setAccessible(true); + idField.set(entity, id); + } +} \ No newline at end of file From 0327e9aa77ce82ca124e3c458af4394d3c8967fe Mon Sep 17 00:00:00 2001 From: Lesly Villanueva Date: Tue, 20 Oct 2026 20:50:10 -0700 Subject: [PATCH 5/6] i think i fixed the comments. i updated recipePatch,recipeService, and the service tests to use Jackson 3's --- .../csumb/cst438/api/record/RecipePatch.java | 2 +- .../cst438/api/service/RecipeService.java | 90 ++----------------- .../cst438/api/service/RecipeServiceTest.java | 2 +- 3 files changed, 8 insertions(+), 86 deletions(-) diff --git a/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java b/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java index 9d86bc8..c6e8965 100644 --- a/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java +++ b/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java @@ -1,7 +1,7 @@ package edu.csumb.cst438.api.record; -import com.fasterxml.jackson.databind.JsonNode; import jakarta.validation.constraints.Pattern; +import tools.jackson.databind.JsonNode; import java.util.Set; diff --git a/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java b/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java index 497dee3..cdc5854 100644 --- a/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java +++ b/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java @@ -1,6 +1,6 @@ package edu.csumb.cst438.api.service; -import com.fasterxml.jackson.databind.JsonNode; +import tools.jackson.databind.JsonNode; import edu.csumb.cst438.api.entity.Ingredient; import edu.csumb.cst438.api.entity.Recipe; import edu.csumb.cst438.api.entity.User; @@ -29,12 +29,6 @@ public class RecipeService { private final RecipeRepository recipeRepository; private final IngredientRepository ingredientRepository; - /** - * Creates a recipe service. - * - * @param recipeRepository repository for recipes - * @param ingredientRepository repository for ingredients - */ public RecipeService( RecipeRepository recipeRepository, IngredientRepository ingredientRepository) { @@ -42,12 +36,6 @@ public RecipeService( this.ingredientRepository = ingredientRepository; } - /** - * Lists recipes using pagination and sorting. - * - * @param pageable pagination and sorting information - * @return a page of recipes - */ @Transactional(readOnly = true) public Page listRecipes(Pageable pageable) { return recipeRepository @@ -55,13 +43,6 @@ public Page listRecipes(Pageable pageable) { .map(RecipeResponse::from); } - /** - * Creates a recipe for the specified user. - * - * @param request recipe creation data - * @param owner user who owns the recipe - * @return the created recipe - */ public RecipeResponse createRecipe( RecipeCreate request, User owner) { @@ -83,13 +64,6 @@ public RecipeResponse createRecipe( ); } - /** - * Retrieves a recipe by ID. - * - * @param recipeId recipe ID - * @return the requested recipe - * @throws EntityNotFoundException if the recipe does not exist - */ @Transactional(readOnly = true) public RecipeResponse getRecipe(Long recipeId) { Recipe recipe = recipeRepository.findById(recipeId) @@ -100,14 +74,6 @@ public RecipeResponse getRecipe(Long recipeId) { return RecipeResponse.from(recipe); } - /** - * Replaces all editable fields of a user's recipe. - * - * @param recipeId recipe ID - * @param request replacement data - * @param owner authenticated user - * @return the updated recipe - */ public RecipeResponse replaceRecipe( Long recipeId, RecipeCreate request, @@ -126,17 +92,6 @@ public RecipeResponse replaceRecipe( return RecipeResponse.from(recipe); } - /** - * Partially updates a user's recipe. - * - * Missing fields retain their existing values. Fields explicitly set - * to null are cleared. - * - * @param recipeId recipe ID - * @param request partial update data - * @param owner authenticated user - * @return the updated recipe - */ public RecipeResponse patchRecipe( Long recipeId, RecipePatch request, @@ -171,26 +126,11 @@ public RecipeResponse patchRecipe( return RecipeResponse.from(recipe); } - /** - * Deletes a user's recipe. - * - * @param recipeId recipe ID - * @param owner authenticated user - */ public void deleteRecipe(Long recipeId, User owner) { Recipe recipe = findOwnedRecipe(recipeId, owner); recipeRepository.delete(recipe); } - /** - * Finds a recipe and verifies that it belongs to the specified user. - * - * @param recipeId recipe ID - * @param owner authenticated user - * @return the owned recipe - * @throws EntityNotFoundException if the recipe does not exist or - * belongs to another user - */ private Recipe findOwnedRecipe(Long recipeId, User owner) { Recipe recipe = recipeRepository.findById(recipeId) .orElseThrow(() -> new EntityNotFoundException( @@ -207,12 +147,6 @@ private Recipe findOwnedRecipe(Long recipeId, User owner) { return recipe; } - /** - * Replaces all ingredients assigned to a recipe. - * - * @param recipe recipe being updated - * @param ingredientIds new ingredient IDs - */ private void replaceIngredients( Recipe recipe, Set ingredientIds) { @@ -227,14 +161,9 @@ private void replaceIngredients( newIngredients.forEach(recipe::addIngredient); } - /** - * Finds all ingredients referenced by their IDs. - * - * @param ingredientIds ingredient IDs - * @return matching ingredients - * @throws EntityNotFoundException if an ingredient is missing - */ - private Set findIngredients(Set ingredientIds) { + private Set findIngredients( + Set ingredientIds) { + List ingredients = ingredientRepository.findAllById(ingredientIds); @@ -247,23 +176,16 @@ private Set findIngredients(Set ingredientIds) { return new HashSet<>(ingredients); } - /** - * Applies PATCH semantics to a nullable text field. - * - * @param value incoming JSON value - * @param currentValue existing database value - * @return the updated value - */ private String patchValue( JsonNode value, String currentValue) { - // The field was omitted, so preserve the old value. + // Field omitted: preserve the current value. if (value == null) { return currentValue; } - // The field was explicitly set to null, so clear it. + // Field explicitly set to null: clear the value. if (value.isNull()) { return null; } diff --git a/api/src/test/java/edu/csumb/cst438/api/service/RecipeServiceTest.java b/api/src/test/java/edu/csumb/cst438/api/service/RecipeServiceTest.java index fdbc6d7..6b0e569 100644 --- a/api/src/test/java/edu/csumb/cst438/api/service/RecipeServiceTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/service/RecipeServiceTest.java @@ -1,6 +1,6 @@ package edu.csumb.cst438.api.service; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import tools.jackson.databind.node.JsonNodeFactory; import edu.csumb.cst438.api.entity.Ingredient; import edu.csumb.cst438.api.entity.Recipe; import edu.csumb.cst438.api.entity.User; From 4f33f72fadbc539e7eac91be95f8e5ef1b4d5982 Mon Sep 17 00:00:00 2001 From: Lesly Villanueva Date: Tue, 20 Oct 2026 21:22:58 -0700 Subject: [PATCH 6/6] Update RecipeCreate schema to use ingredientIds --- docs/openapi.yaml | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 8214a70..0198e81 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -787,16 +787,18 @@ components: RecipeCreate: description: Body for POST and PUT. PUT replaces every field. type: object - required: [name, ingredients, measurements, instructions] + required: [name, ingredientIds, measurements, instructions] properties: name: type: string minLength: 1 example: Brown Sugar Oatmeal - ingredients: + ingredientIds: type: array items: - $ref: '#/components/schemas/Ingredient' + type: integer + format: int64 + example: [1, 2, 3] measurements: type: string nullable: true @@ -823,10 +825,16 @@ components: type: object minProperties: 1 properties: - ingredients: + name: + type: string + minLength: 1 + example: Updated Recipe Name + ingredientIds: type: array items: - $ref: '#/components/schemas/Ingredient' + type: integer + format: int64 + example: [1, 3] measurements: type: string nullable: true