C'est un pAPI.

This commit is contained in:
MarcEricMartel
2022-11-05 07:55:09 -07:00
parent 0b7b9689b1
commit 4608cb5de8
5 changed files with 230 additions and 9 deletions

View File

@@ -42,8 +42,13 @@ public class ProductController : ControllerBase {
}
#endregion
#region API Methods
[EnableCors("_myAllowSpecificOrigins"), Route("Quantity"), HttpGet(Name = "Product"), AllowAnonymous]
public ActionResult<uint> ProdCount(int id) {
return _context.Products.FirstOrDefault(x => x.Id == id).Quantity;
}
[EnableCors("_myAllowSpecificOrigins"), HttpGet(Name = "Product"), AllowAnonymous]
public ActionResult<ProductViewModel> Get(int id) {
ProductModel prod;
@@ -78,10 +83,20 @@ public class ProductController : ControllerBase {
}
[EnableCors("_myAllowSpecificOrigins"), HttpPatch(Name = "Product")]
public ActionResult<ProductModel> Patch(ProductModel prod) {
public async Task<ActionResult<ProductModel>> Patch([FromForm] ProductModel prod) {
string? oldImage = "";
try {
if (prod.ImageFile is not null) {
oldImage = _context.Products.FirstOrDefault(x => x.Id == prod.Id).ImageName;
if (oldImage == prod.ImageName)
oldImage = "";
prod.ImageName = await SaveImage(prod.ImageFile);
}
_context.Products.Update(prod);
_context.SaveChanges();
if (oldImage is not null and not "")
DeleteImages(oldImage);
}
catch (Exception e) {
_logger.LogError(8, e.Message);
@@ -92,10 +107,13 @@ public class ProductController : ControllerBase {
}
[EnableCors("_myAllowSpecificOrigins"), HttpDelete(Name = "Product")]
public ActionResult<int> DeleteProduct(int id) {
public ActionResult<int> Delete(int id) {
try {
_context.Products.Remove(_context.Products.Where(x => x.Id == id).First());
var prod = _context.Products.Where(x => x.Id == id).First();
string imageName = prod.ImageName;
_context.Products.Remove(prod);
_context.SaveChanges();
DeleteImages(imageName);
}
catch (Exception e) {
_logger.LogError(8, e.Message);
@@ -137,5 +155,13 @@ public class ProductController : ControllerBase {
}
}
private void DeleteImages(string imageName) {
var files = System.IO.Directory.GetFiles(_hostEnvironment.ContentRootPath + "/Images")
.Where(x => x.Contains(imageName)).ToArray();
foreach (var file in files)
System.IO.File.Delete(_hostEnvironment.ContentRootPath + "/Images/" + file);
}
#endregion
}