102 lines
3.4 KiB
C#
102 lines
3.4 KiB
C#
// все про товары
|
||
using DEMO.Data; // база
|
||
using DEMO.Models; // товары
|
||
using Microsoft.AspNetCore.Mvc; // контроллер
|
||
using Microsoft.EntityFrameworkCore; // поиск в базе
|
||
|
||
namespace DEMO.Controllers;
|
||
|
||
[ApiController] // это api
|
||
[Route("api/[controller]")] // адрес будет api/products
|
||
public class ProductsController : ControllerBase
|
||
{
|
||
private readonly AppDbContext _context; // база
|
||
|
||
// запоминаю базу
|
||
public ProductsController(AppDbContext context)
|
||
{
|
||
_context = context;
|
||
}
|
||
|
||
// отдать все товары, GET api/products
|
||
[HttpGet]
|
||
public async Task<IActionResult> GetProducts()
|
||
{
|
||
// беру товары и сразу их категории
|
||
var products = await _context.Products
|
||
.Include(p => p.Category)
|
||
.ToListAsync();
|
||
|
||
return Ok(products); // отдаю список
|
||
}
|
||
|
||
// добавить товар, POST api/products
|
||
[HttpPost]
|
||
public async Task<IActionResult> CreateProduct(Product product) // приходит товар
|
||
{
|
||
product.Name = (product.Name ?? "").Trim(); // убираю пробелы
|
||
|
||
if (product.Name.Length < 2)
|
||
return BadRequest("Название слишком короткое, надо минимум 2 буквы.");
|
||
|
||
if (product.Price <= 0)
|
||
return BadRequest("Цена должна быть больше нуля.");
|
||
|
||
// проверяю есть ли такая категория
|
||
var categoryExists = await _context.Categories
|
||
.AnyAsync(c => c.Id == product.CategoryId);
|
||
|
||
if (!categoryExists)
|
||
return BadRequest("Такой категории нет.");
|
||
|
||
_context.Products.Add(product); // добавляю
|
||
await _context.SaveChangesAsync(); // сохраняю
|
||
|
||
return Ok(product); // отдаю обратно
|
||
}
|
||
|
||
// изменить товар, PUT api/products/5
|
||
[HttpPut("{id}")]
|
||
public async Task<IActionResult> UpdateProduct(int id, Product product)
|
||
{
|
||
// ищу старый товар
|
||
var existingProduct = await _context.Products.FindAsync(id);
|
||
|
||
if (existingProduct == null)
|
||
return NotFound(); // нет такого
|
||
|
||
product.Name = (product.Name ?? "").Trim();
|
||
|
||
if (product.Name.Length < 2)
|
||
return BadRequest("Название слишком короткое, надо минимум 2 буквы.");
|
||
|
||
if (product.Price <= 0)
|
||
return BadRequest("Цена должна быть больше нуля.");
|
||
|
||
// меняю поля
|
||
existingProduct.Name = product.Name;
|
||
existingProduct.Price = product.Price;
|
||
existingProduct.CategoryId = product.CategoryId;
|
||
|
||
await _context.SaveChangesAsync(); // сохраняю
|
||
|
||
return Ok(existingProduct);
|
||
}
|
||
|
||
// удалить товар, DELETE api/products/5
|
||
[HttpDelete("{id}")]
|
||
public async Task<IActionResult> DeleteProduct(int id)
|
||
{
|
||
// ищу товар
|
||
var product = await _context.Products.FindAsync(id);
|
||
|
||
if (product == null)
|
||
return NotFound();
|
||
|
||
_context.Products.Remove(product); // удаляю
|
||
await _context.SaveChangesAsync(); // сохраняю
|
||
|
||
return NoContent(); // все хорошо, отдавать нечего
|
||
}
|
||
}
|