GGMM/GrossesMitaines/GrossesMitainesAPI/Controllers/ProductController.cs
2022-10-21 14:52:25 -07:00

91 lines
2.6 KiB
C#

using GrossesMitainesAPI.Models;
using System.Linq;
using GrossesMitainesAPI.Data;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using GrossesMitainesAPI.Services;
namespace GrossesMitainesAPI.Controllers;
[EnableCors("_myAllowSpecificOrigins")]
[ApiController, Route("api/[controller]")]
public class ProductController : ControllerBase {
private readonly ILogger<ProductController> _logger;
private readonly InventoryContext _context;
private readonly DatabaseCacheService _cache;
public ProductController(ILogger<ProductController> logger, InventoryContext context, DatabaseCacheService cache) {
_logger = logger;
_context = context;
_cache = cache;
}
[EnableCors("_myAllowSpecificOrigins")]
[HttpGet(Name = "Product"), AllowAnonymous]
public ActionResult<Product> Get(int id) {
Product prod;
try {
prod = _context.Products.Where(x => x.Id == id).First();
}
catch (Exception e) {
_logger.LogError(8, e.Message);
return NotFound();
}
return prod;
}
[EnableCors("_myAllowSpecificOrigins")]
[HttpPost(Name = "Product")]
public ActionResult<Product> Post(Product prod) {
if (prod.Price <= prod.PromoPrice)
prod.PromoPrice = prod.Price - 0.01M;
try {
_context.Products.Add(prod);
_context.SaveChanges();
_cache.askForRefresh();
}
catch (Exception e) {
_logger.LogError(8, e.Message);
return BadRequest(e.Message);
}
return prod;
}
[EnableCors("_myAllowSpecificOrigins")]
[HttpPut(Name = "Product")]
public ActionResult<Product> Put(Product prod) {
try {
_context.Products.Update(prod);
_context.SaveChanges();
_cache.askForRefresh();
}
catch (Exception e) {
_logger.LogError(8, e.Message);
return BadRequest(e.Message);
}
return prod;
}
[EnableCors("_myAllowSpecificOrigins")]
[HttpDelete(Name = "Product")]
public ActionResult<int> DeleteProduct(int id) {
try {
_context.Products.Remove(_context.Products.Where(x => x.Id == id).First());
_context.SaveChanges();
_cache.askForRefresh();
}
catch (Exception e) {
_logger.LogError(8, e.Message);
return BadRequest(e.Message);
}
return id;
}
}