ShoppingApp/Weifer.ShoppingApp.API/RestApi/ShoppingItemApiController.cs
marcus db241716aa implementation for:
main list loading
add item
2024-03-02 21:29:11 +01:00

69 lines
2.2 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Weifer.Database.EF;
using Weifer.Database.EF.Entitys;
using Weifer.ShoppingApp.API.Models;
namespace Weifer.ShoppingApp.API.RestApi
{
[ApiController]
[Route("api/[controller]")]
public class ShoppingItemApiController : ControllerBase
{
public readonly DatabaseContext dbContext;
public ShoppingItemApiController(DatabaseContext dbContext)
{
this.dbContext = dbContext;
}
[HttpGet("getItems")]
public async Task<IActionResult> GetMainItems([FromQuery] string customerId)
{
if (!Guid.TryParse(customerId, out var guidCustomerId))
{
return BadRequest("Invalid Customer ID");
}
var shoppingItems = await dbContext.ShoppingLists
.Where(x => x.CustomerId == guidCustomerId && x.ShoppingListName == "MainList")
.Include(x => x.ShoppingItems)
.SelectMany(x => x.ShoppingItems) // Wählt nur die ShoppingItems aus
.ToListAsync();
return Ok(shoppingItems);
}
[HttpPost("addMainItem")]
public async Task<IActionResult> AddMainItem([FromBody] AddItemRequest request)
{
if (!Guid.TryParse(request.CustomerId, out var guidCustomerId))
{
return BadRequest("Invalid Customer ID");
}
var itemToAdd = new ShoppingItem
{
ShoppingItemId = Guid.NewGuid(), // Generate a new GUID for the item
ShoppingListId = await dbContext.ShoppingLists
.Where(x => x.CustomerId == guidCustomerId && x.ShoppingListName == "MainList")
.Select(x => x.ShoppingListId)
.FirstOrDefaultAsync(),
Description = request.ItemName,
Number = 1,
Purchased = false,
};
dbContext.ShoppingItems.Add(itemToAdd);
await dbContext.SaveChangesAsync();
return Ok();
}
}
public class AddItemRequest
{
public string CustomerId { get; set; }
public string ItemName { get; set; }
}
}