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
5 changes: 5 additions & 0 deletions api/src/main/java/edu/csumb/cst438/api/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ public SecurityFilterChain securityFilterChain(
.requestMatchers(HttpMethod.GET, "/api/v1/users/{userid}").hasRole("ADMIN")
.requestMatchers(HttpMethod.PATCH, "/api/v1/users/{userid}").hasRole("ADMIN")
.requestMatchers(HttpMethod.DELETE, "/api/v1/users/{userid}").hasRole("ADMIN")
// Anyone can browse ingredients.
.requestMatchers(HttpMethod.GET, "/api/v1/ingredients", "/api/v1/ingredients/**").permitAll()
//only authenticated users can add ingredients
.requestMatchers(HttpMethod.POST, "/api/v1/ingredients").authenticated()

.anyRequest().authenticated()
)
.exceptionHandling(ex -> ex
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package edu.csumb.cst438.api.controller;

import edu.csumb.cst438.api.record.IngredientCreate;
import edu.csumb.cst438.api.record.IngredientResponse;
import edu.csumb.cst438.api.service.IngredientService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import org.springframework.data.web.PagedModel;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;

@RestController
@RequestMapping("/api/v1/ingredients")
public class IngredientController {

private final IngredientService ingredientService;

public IngredientController(IngredientService ingredientService) {
this.ingredientService = ingredientService;
}

@GetMapping
public PagedModel<IngredientResponse> listIngredients(
@RequestParam(defaultValue = "0")
@Min(0) int page,

@RequestParam(defaultValue = "20")
@Min(1)
@Max(100) int size) {

return new PagedModel<>(
ingredientService.list(page, size)
);
}

@PostMapping
public ResponseEntity<IngredientResponse> createIngredient(
@Valid @RequestBody IngredientCreate request) {

IngredientResponse created =
ingredientService.create(request);
Comment thread
leslyVillanueva1020 marked this conversation as resolved.
Resolved

return ResponseEntity
.created(URI.create(
"/api/v1/ingredients/" + created.getId()
))
.body(created);
}
}
33 changes: 28 additions & 5 deletions api/src/main/java/edu/csumb/cst438/api/entity/Ingredient.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,37 @@
import jakarta.persistence.*;

import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

@Entity
@Table(name="ingredients")
@Table(name = "ingredients")
public class Ingredient {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name="ingredient_name", nullable = false, unique = true)
@Column(name = "ingredient_name", nullable = false)
private String ingredientName;

@Column(
name = "ingredient_name_normalized",
nullable = false,
unique = true
)
private String normalizedName;

@ManyToMany(mappedBy = "ingredients")
private Set<Recipe> recipes = new HashSet<>();

protected Ingredient() {}
protected Ingredient() {
}

public Ingredient(String ingredientName) {
this.ingredientName = ingredientName;
setIngredientName(ingredientName);
}

public Long getId() {
return id;
}
Expand All @@ -34,6 +44,7 @@ public String getIngredientName() {

public void setIngredientName(String ingredientName) {
this.ingredientName = ingredientName;
this.normalizedName = normalize(ingredientName);
}

public Set<Recipe> getRecipes() {
Expand All @@ -47,4 +58,16 @@ void addRecipe(Recipe recipe) {
void removeRecipe(Recipe recipe) {
recipes.remove(recipe);
}
}

@PrePersist
@PreUpdate
private void updateNormalizedName() {
this.normalizedName = normalize(this.ingredientName);
}

private static String normalize(String value) {
return value == null
? null
: value.trim().toLowerCase(Locale.ROOT);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package edu.csumb.cst438.api.record;

import jakarta.validation.constraints.NotBlank;

public record IngredientCreate(
@NotBlank String ingredientName
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package edu.csumb.cst438.api.record;

import edu.csumb.cst438.api.entity.Ingredient;

public record IngredientResponse(
Long id,
String ingredientName
) {
public static IngredientResponse from(Ingredient ingredient) {
return new IngredientResponse(
ingredient.getId(),
ingredient.getIngredientName()
);
}

public Long getId() {
return id;
}

public String getIngredientName() {
return ingredientName;
}
}
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.Ingredient;
import org.springframework.data.jpa.repository.JpaRepository;

public interface IngredientRepository
extends JpaRepository<Ingredient, Long> {

boolean existsByIngredientNameIgnoreCase(String ingredientName);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package edu.csumb.cst438.api.service;

import edu.csumb.cst438.api.entity.Ingredient;
import edu.csumb.cst438.api.record.IngredientCreate;
import edu.csumb.cst438.api.record.IngredientResponse;
import edu.csumb.cst438.api.repository.IngredientRepository;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;

@Service
@Transactional
public class IngredientService {

private final IngredientRepository ingredientRepository;

public IngredientService(IngredientRepository ingredientRepository) {
this.ingredientRepository = ingredientRepository;
}

@Transactional(readOnly = true)
public Page<IngredientResponse> listIngredients(Pageable pageable) {
return ingredientRepository
.findAll(pageable)
.map(IngredientResponse::from);
}

@Transactional(readOnly = true)
public Page<IngredientResponse> list(int page, int size) {
return listIngredients(PageRequest.of(page, size));
}

public IngredientResponse create(IngredientCreate request) {
if (ingredientRepository.existsByIngredientNameIgnoreCase(
request.ingredientName())) {

throw new ResponseStatusException(
HttpStatus.CONFLICT,
"Ingredient already exists"
);
}

Ingredient ingredient =
new Ingredient(request.ingredientName());

try {
Ingredient savedIngredient =
ingredientRepository.saveAndFlush(ingredient);

Comment thread
leslyVillanueva1020 marked this conversation as resolved.
Resolved
return IngredientResponse.from(savedIngredient);

} catch (DataIntegrityViolationException exception) {
throw new ResponseStatusException(
HttpStatus.CONFLICT,
"Ingredient already exists",
exception
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package edu.csumb.cst438.api.service;

import edu.csumb.cst438.api.record.IngredientResponse;
import edu.csumb.cst438.api.entity.Ingredient;
import edu.csumb.cst438.api.repository.IngredientRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
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.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class IngredientServiceTest {

@Mock
private IngredientRepository ingredientRepository;

@InjectMocks
private IngredientService ingredientService;

@Test
void listIngredientsReturnsIngredientResponses() {
Pageable pageable = PageRequest.of(0, 20);
Ingredient ingredient = new Ingredient("Flour");

Page<Ingredient> ingredientPage =
new PageImpl<>(List.of(ingredient));

when(ingredientRepository.findAll(pageable))
.thenReturn(ingredientPage);

Page<IngredientResponse> result =
ingredientService.listIngredients(pageable);

assertEquals(1, result.getContent().size());
assertEquals(
"Flour",
result.getContent().get(0).getIngredientName()
);

verify(ingredientRepository).findAll(pageable);
}
}
Loading