From 135e9934e12ffc76f4548d5d1f8ee282515a2a9b Mon Sep 17 00:00:00 2001 From: Paweł Bernaciak Date: Sun, 22 Oct 2023 15:35:37 +0200 Subject: Add element controller --- .../Controllers/ElementController.cs | 63 ++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 backend/Elements.Backend/Controllers/ElementController.cs (limited to 'backend') diff --git a/backend/Elements.Backend/Controllers/ElementController.cs b/backend/Elements.Backend/Controllers/ElementController.cs new file mode 100644 index 0000000..890f614 --- /dev/null +++ b/backend/Elements.Backend/Controllers/ElementController.cs @@ -0,0 +1,63 @@ +using System.Buffers.Text; +using System.Text.Json; +using Elements.Data; +using Elements.Data.Models; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace Elements.Backend.Controllers; + +[ApiController] +[Route("[controller]/[action]")] +public class ElementController : ControllerBase +{ + private readonly ApplicationDbContext _dbContext; + + public ElementController(ApplicationDbContext dbContext) + { + _dbContext = dbContext; + } + + [Route("/element/{id:int}")] + [HttpGet] + public async Task GetElement(int id) + { + Element? element = await _dbContext.Elements + .Include(e => e.User) + .FirstOrDefaultAsync(e => e.Id == id); + if (element == null) + return NotFound(); + + var response = new + { + Id = element.Id, + Name = element.Name, + CreatorName = element.User.Name, + State = element.State, + Icon = Convert.ToBase64String(element.IconPng) + }; + + var serializeOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; + return Ok(JsonSerializer.Serialize(response, serializeOptions)); + } + + [Route("/element/combine")] + [HttpGet] + public async Task GetByCombination(int firstElementId, int secondElementId) + { + bool firstExists = await _dbContext.Elements.AnyAsync(e => e.Id == firstElementId); + bool secondExists = await _dbContext.Elements.AnyAsync(e => e.Id == secondElementId); + if (!firstExists || !secondExists) + return BadRequest(); + + Recipe? recipe = await _dbContext.Recipes.Include(r => r.Result).FirstOrDefaultAsync(r => + (r.FirstIngredient.Id == firstElementId && r.SecondIngredient.Id == secondElementId) || + (r.FirstIngredient.Id == secondElementId && r.SecondIngredient.Id == firstElementId)); + if (recipe == null) + return NotFound(); + + var serializeOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; + return Ok(JsonSerializer.Serialize(recipe.Result, serializeOptions)); + } +} \ No newline at end of file -- cgit v1.2.3