Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<RecipeResponse> 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<RecipeResponse> 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<Void> 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)
);
}
}
19 changes: 19 additions & 0 deletions api/src/main/java/edu/csumb/cst438/api/record/RecipeCreate.java
Original file line number Diff line number Diff line change
@@ -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<Long> ingredientIds,
Comment thread
leslyVillanueva1020 marked this conversation as resolved.
Resolved
Comment thread
leslyVillanueva1020 marked this conversation as resolved.
Resolved

String measurements,

String instructions
) {
}
21 changes: 21 additions & 0 deletions api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package edu.csumb.cst438.api.record;

import jakarta.validation.constraints.Pattern;
import tools.jackson.databind.JsonNode;

import java.util.Set;

public record RecipePatch(
@Pattern(
regexp = ".*\\S.*",
message = "Name must not be blank"
)
String name,

Set<Long> ingredientIds,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same review at RecipeCreate

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still appears unresolved. Using ingredientIds here is fine, but docs/openapi.yaml still defines ingredients as an array of objects in both RecipeCreate and RecipePatch. Please update those request schemas to match the code before resolving this comment.


JsonNode measurements,

JsonNode instructions
) {
}
Original file line number Diff line number Diff line change
@@ -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<IngredientResponse> 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()
);
}
}
Original file line number Diff line number Diff line change
@@ -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<Recipe, Long> {
}
Loading
Loading