diff options
| author | Paweł Bernaciak <pawelbernaciak@zohomail.eu> | 2023-10-22 15:35:37 +0200 |
|---|---|---|
| committer | Paweł Bernaciak <pawelbernaciak@zohomail.eu> | 2023-10-22 15:35:37 +0200 |
| commit | 135e9934e12ffc76f4548d5d1f8ee282515a2a9b (patch) | |
| tree | 24d237754a7c814fb71fee61b032eb1a6456d2fe /backend/Elements.Backend/Controllers/ElementController.cs | |
| parent | cc4d58a1bf2fff24f9979c92118fbf23afe443f4 (diff) | |
Add element controller
Diffstat (limited to 'backend/Elements.Backend/Controllers/ElementController.cs')
| -rw-r--r-- | backend/Elements.Backend/Controllers/ElementController.cs | 63 |
1 files changed, 63 insertions, 0 deletions
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<IActionResult> 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<IActionResult> 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 |
