Implemented Optional fields and rewrote tests

This commit is contained in:
Rithvik Sriram 2026-01-08 22:38:52 +01:00
commit 4dc44fb6e9

View file

@ -126,24 +126,32 @@ public class RecipeController {
* Recipe name and limits the result to a set amount of results.
* @param search - name of the recipe to be searched for.
* @param limit - limit of the results queried for.
* @param lang - stores the info of the language of the user to provide server support/
* @return - returns a ResponseEntity with a List of Recipes and an HTTP 200 ok status.
*/
public ResponseEntity<List<Recipe>> getRecipes(
@RequestParam(required = false) String search,
@RequestParam(required = false) Integer limit){
@RequestParam Optional<String> search,
@RequestParam Optional<Integer> limit,
@RequestParam Optional<String> lang){
List<Recipe> recipes = recipeRepository.findAll();
if(search != null && !search.trim().isEmpty()){ // if search isn't null or empty perform the filtering process
String lowercaseSearch = search.toLowerCase();
recipes = recipes.stream().filter(recipe -> recipe.getName()
.toLowerCase()
.contains(lowercaseSearch))
List<Recipe> finalRecipes = recipes;
recipes = search
.filter(s -> !s.trim().isEmpty()) // filters recipes if the string is not empty by doing a lowercase search
.map(s -> {
String lowercaseSearch = s.toLowerCase();
return finalRecipes.stream()
.filter(recipe ->
recipe.getName().toLowerCase().contains(lowercaseSearch)
)
.toList();
}
if(limit != null && limit<recipes.size()){ // Limit the results if the limit is provided
recipes = recipes.stream().limit(limit).toList();
}
})
.orElse(recipes);
recipes = limit // filters based on limit if provided
.filter(l -> l < finalRecipes.size())
.map(l -> finalRecipes.stream().limit(l).toList())
.orElse(recipes);
return ResponseEntity.ok(recipes);
}