Change Search Logic

This commit is contained in:
franc
2025-04-16 11:17:42 +02:00
parent f64f1bf1ee
commit 2f33951c4e
2 changed files with 18 additions and 24 deletions
@@ -13,10 +13,10 @@
Task RemoveIngredientFromRecipeAsync(Guid recipeId, Guid ingredientId);
Task<IEnumerable<Recipe>> GetRecipesByNameAndIngredientAsync(string name, string ingredient);
Task<IReadOnlyCollection<Recipe>> GetRecipesByDifficultyAsync(Difficulty? difficulty);
Task<Recipe> CreateRecipeForCategoryAsync(Category category, string name, string description, Difficulty difficulty, int servings, TimeSpan preparationTime, TimeSpan cookingTime);
Task<IEnumerable<Recipe>> GetRecipesBySearchQueryAsync(string query);
}
}
@@ -147,30 +147,24 @@
await _context.SaveChangesAsync();
}
public async Task<IEnumerable<Recipe>> GetRecipesByNameAndIngredientAsync(string name, string ingredient)
public async Task<IEnumerable<Recipe>> GetRecipesBySearchQueryAsync(string query)
{
var query = _context.Recipes
if (string.IsNullOrWhiteSpace(query))
{
return await _context.Recipes
.Include(r => r.RecipeIngredients)
.ThenInclude(ri => ri.Ingredient)
.AsQueryable();
if (!string.IsNullOrWhiteSpace(name))
{
query = query.Where(r => r.Name.Contains(name, StringComparison.OrdinalIgnoreCase));
.ToListAsync();
}
if (!string.IsNullOrWhiteSpace(ingredient))
{
var ingredientMatches = await _ingredientRepository.GetIngredientsByNameAsync(ingredient);
var ingredientIds = ingredientMatches.Select(i => i.Id).ToList();
query = query.ToLower();
if (ingredientIds.Any())
{
query = query.Where(r => r.RecipeIngredients.Any(ri => ingredientIds.Contains(ri.Ingredient.Id)));
}
}
return await query.ToListAsync();
return await _context.Recipes
.Include(r => r.RecipeIngredients)
.ThenInclude(ri => ri.Ingredient)
.Where(r => r.Name.ToLower().Contains(query) ||
r.RecipeIngredients.Any(ri => ri.Ingredient.Name.ToLower().Contains(query)))
.ToListAsync();
}
public async Task<IReadOnlyCollection<Recipe>> GetRecipesByDifficultyAsync(Difficulty? difficulty)