GGMM/GrossesMitaines/GrossesMitainesAPI/Controllers/SearchController.cs
2022-10-18 10:25:08 -07:00

56 lines
2.1 KiB
C#

using Microsoft.AspNetCore.Mvc;
using GrossesMitainesAPI.Models;
using System.Linq;
using GrossesMitainesAPI.Data;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
namespace GrossesMitainesAPI.Controllers;
[EnableCors("_myAllowSpecificOrigins")]
[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;
}
[EnableCors("_myAllowSpecificOrigins")]
[HttpPost(Name = "Search")]
public IEnumerable<Product> Post(string query, bool? preview) {
const int PREVIEW = 3;
List<Product> products = new();
query = query.Trim();
try { // Pour faire une liste priorisée.
if (preview.HasValue && preview == true)
products = _context.Products.Where(x => x.Title.Contains(query)).Take(PREVIEW).ToList();
else {
products = _context.Products.Where(x => x.Title.Replace(".", " ")
.Replace(",", " ")
.ToUpper()
.Contains(" " + query.ToUpper() + " "))
.ToList();
foreach (Product prod in _context.Products.Where(x => x.Category.Contains(query)).ToList()) {
if (!products.Contains(prod))
products.Add(prod);
}
foreach (Product prod in _context.Products.Where(x => x.Description.Contains(query)).ToList()) {
if (!products.Contains(prod))
products.Add(prod);
}
}
} catch (Exception e) {
_logger.LogError(8, e.Message);
}
return products;
}
}