GGMM/GrossesMitaines/GrossesMitainesAPI/Controllers/SearchController.cs

45 lines
1.5 KiB
C#
Raw Normal View History

2022-10-09 14:23:46 -04:00
using Microsoft.AspNetCore.Mvc;
using GrossesMitainesAPI.Models;
using System.Linq;
using GrossesMitainesAPI.Data;
using Microsoft.Extensions.Logging;
2022-10-16 11:25:21 -04:00
using Microsoft.AspNetCore.Authorization;
2022-10-18 10:08:23 -04:00
using Microsoft.AspNetCore.Cors;
2022-10-09 14:23:46 -04:00
namespace GrossesMitainesAPI.Controllers;
2022-10-18 10:08:23 -04:00
[EnableCors("_myAllowSpecificOrigins")]
2022-10-09 14:23:46 -04:00
[ApiController, Route("api/[controller]")]
public class SearchController : Controller {
private readonly ILogger<SearchController> _logger;
private readonly InventoryContext _context;
public SearchController(ILogger<SearchController> logger, InventoryContext context) {
_logger = logger;
_context = context;
}
2022-10-18 10:08:23 -04:00
[EnableCors("_myAllowSpecificOrigins")]
2022-10-09 14:23:46 -04:00
[HttpPost(Name = "Search")]
2022-10-16 20:33:58 -04:00
public IEnumerable<Product> Post(string query, bool? preview) {
2022-10-18 12:39:04 -04:00
const int PREVIEW = 3;
2022-10-09 14:23:46 -04:00
HashSet<Product> products = new();
query = query.Trim();
try { // Pour faire une liste priorisée.
2022-10-16 20:33:58 -04:00
if (preview.HasValue && preview == true)
2022-10-18 12:39:04 -04:00
products = _context.Products.Where(x => x.Title.Contains(query)).Take(PREVIEW).ToHashSet();
2022-10-16 20:33:58 -04:00
else {
products.Concat(_context.Products.Where(x => x.Title.Contains(query)).ToHashSet());
products.Concat(_context.Products.Where(x => x.Category.Contains(query)).ToHashSet());
products.Concat(_context.Products.Where(x => x.Description.Contains(query)).ToHashSet());
}
2022-10-09 14:23:46 -04:00
} catch (Exception e) {
_logger.LogError(8, e.Message);
}
return products;
}
}