Files
Aberwyn/Nevyn/Controllers/ShoppingListsController.cs
2023-01-29 12:04:01 +01:00

128 lines
3.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Nevyn.Models;
namespace Nevyn.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ShoppingListsController : ControllerBase
{
private readonly ShoppingContext _context;
public ShoppingListsController(ShoppingContext context)
{
_context = context;
}
// GET: api/ShoppingLists
[HttpGet]
public async Task<ActionResult<IEnumerable<ShoppingListDTO>>> GetUpdateShopping()
{
return await _context.UpdateShopping.Select(x => ItemToDTO(x)).ToListAsync();
}
// GET: api/ShoppingLists/5
[HttpGet("{id}")]
public async Task<ActionResult<ShoppingListDTO>> GetShoppingList(long id)
{
var shoppingList = await _context.UpdateShopping.FindAsync(id);
if (shoppingList == null)
{
return NotFound();
}
return ItemToDTO(shoppingList);
}
// PUT: api/ShoppingLists/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutShoppingList(long id, ShoppingListDTO shoppingListDTO)
{
if (id != shoppingListDTO.Id)
{
return BadRequest();
}
//_context.Entry(shoppingList).State = EntityState.Modified;
var shoppingList = await _context.UpdateShopping.FindAsync(id);
if (shoppingList == null)
{
return NotFound();
}
shoppingList.Name = shoppingListDTO.Name;
shoppingList.IsComplete = shoppingListDTO.IsComplete;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException) when (!ShoppingListExists(id))
{
return NotFound();
}
return NoContent();
}
// POST: api/ShoppingLists
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<ShoppingListDTO>> PostShoppingList(ShoppingListDTO shoppingListDTO)
{
var shoppingList = new ShoppingList
{
IsComplete = shoppingListDTO.IsComplete,
Name = shoppingListDTO.Name
};
_context.UpdateShopping.Add(shoppingList);
await _context.SaveChangesAsync();
return CreatedAtAction(
nameof(GetShoppingList),
new { id = shoppingList.Id },
ItemToDTO(shoppingList));
}
// DELETE: api/ShoppingLists/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteShoppingList(long id)
{
var shoppingList = await _context.UpdateShopping.FindAsync(id);
if (shoppingList == null)
{
return NotFound();
}
_context.UpdateShopping.Remove(shoppingList);
await _context.SaveChangesAsync();
return NoContent();
}
private bool ShoppingListExists(long id)
{
return _context.UpdateShopping.Any(e => e.Id == id);
}
private static ShoppingListDTO ItemToDTO(ShoppingList shoppingList) =>
new ShoppingListDTO
{
Id = shoppingList.Id,
Name = shoppingList.Name,
IsComplete = shoppingList.IsComplete
};
}
}