GGMM/GrossesMitaines/GrossesMitainesAPI/Controllers/ProductController.cs

97 lines
2.8 KiB
C#
Raw Normal View History

2022-10-08 15:04:29 -04:00
using Microsoft.AspNetCore.Mvc;
using GrossesMitainesAPI.Models;
using System.Linq;
using GrossesMitainesAPI.Data;
using Microsoft.Extensions.Logging;
namespace GrossesMitainesAPI.Controllers;
[ApiController, Route("api/[controller]")]
public class ProductController : Controller {
private readonly ILogger<ProductController> _logger;
private readonly InventoryContext _context;
public ProductController(ILogger<ProductController> logger, InventoryContext context) {
_logger = logger;
_context = context;
}
[HttpGet(Name = "Product")]
public Product Get(int id) {
Product prod;
try {
prod = _context.Products.Where(x => x.Id == id).First();
} catch (Exception e) {
_logger.LogError(8, e.Message);
prod = new Product();
}
return prod;
}
[HttpPost(Name = "Product")]
2022-10-09 13:18:39 -04:00
public void Post(string title, string description, decimal price, string imagename) {
Product prod = new() {
Title = title,
Description = description,
Price = price,
ImageName = imagename
};
2022-10-08 15:04:29 -04:00
try {
_context.Products.Add(prod);
} catch (Exception e) {
_logger.LogError(8, e.Message);
}
}
2022-10-08 16:05:23 -04:00
[HttpPut(Name = "Product")]
2022-10-09 13:18:39 -04:00
public void Put(int id, string title, string description, decimal? price, string imagename) {
2022-10-08 16:05:23 -04:00
try {
2022-10-09 13:18:39 -04:00
Product prod = _context.Products.Where(x => x.Id == id).First();
if (title != null || title != "")
prod.Title = title;
if (description != null || description != "")
prod.Description = description;
if (price.HasValue || price > 0)
prod.Price = (decimal)price;
if (imagename != null || imagename != "")
prod.ImageName = imagename;
_context.Products.Update(prod);
} catch (Exception e) {
_logger.LogError(8, e.Message);
}
}
[HttpPatch(Name = "Product")]
public void Patch(int id, string title, string description, decimal? price, string imagename) {
try {
Product prod = _context.Products.Where(x => x.Id == id).First();
if (title != null)
prod.Title = title;
else prod.Title = "";
if (description != null)
prod.Description = description;
else prod.Description = "";
if (price.HasValue || price > 0)
prod.Price = (decimal)price;
else prod.Price = 0.01M;
if (imagename != null)
prod.ImageName = imagename;
else prod.ImageName = "";
2022-10-08 16:05:23 -04:00
_context.Products.Update(prod);
} catch (Exception e) {
_logger.LogError(8, e.Message);
}
}
2022-10-08 15:04:29 -04:00
}