Created IngredientService

This commit is contained in:
Oskar Rasieński 2026-01-07 23:49:42 +01:00
commit b7116a0882
2 changed files with 67 additions and 0 deletions

View file

@ -12,5 +12,7 @@ public interface IngredientRepository extends JpaRepository<Ingredient, Long> {
List<Ingredient> findAllByOrderByNameAsc();
Page<Ingredient> findAllByOrderByNameAsc(Pageable pageable);
Optional<Ingredient> findByName(String name);
boolean existsByName(String name);
}

View file

@ -0,0 +1,65 @@
package service;
import commons.Ingredient;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import server.database.IngredientRepository;
import java.util.List;
import java.util.Optional;
@Service
public class IngredientService {
IngredientRepository ingredientRepository;
public IngredientService(IngredientRepository ingredientRepository) {
this.ingredientRepository = ingredientRepository;
}
public Optional<Ingredient> findById(Long id) {
return ingredientRepository.findById(id);
}
public List<Ingredient> findAll() {
return ingredientRepository.findAll();
}
public List<Ingredient> findAll(int limit) {
return ingredientRepository.findAll(PageRequest.of(0, limit)).toList();
}
/**
* Creates a new ingredient. Returns empty if the recipe with the same name or id already exists.
* @param ingredient Ingredient to be saved in the db.
* @return The created ingredient (the ingredient arg with a new assigned id) or empty if it already exists in db.
*/
public Optional<Ingredient> create(Ingredient ingredient) {
if (ingredientRepository.existsByName(ingredient.getName()) ||
ingredientRepository.existsById(ingredient.getId())) {
return Optional.empty();
}
return Optional.of(ingredientRepository.save(ingredient));
}
/**
* Updates an ingredient. The ingredient with the provided id will be replaced (in db) with the provided ingredient.
* @param id id of the ingredient to update.
* @param ingredient Ingredient to be saved in the db.
* @return The created ingredient (the ingredient arg with a new assigned id.)
*/
public Optional<Ingredient> update(Long id, Ingredient ingredient) {
assert id.equals(ingredient.getId()) :
"The id of the updated ingredient doesn't match the provided ingredient's id.";
if (!ingredientRepository.existsById(id)) {
return Optional.empty();
}
return Optional.of(ingredientRepository.save(ingredient));
}
public void delete(Long id) {
ingredientRepository.deleteById(id);
}
}