Files
GerbilManager/GerbilManagerWebAPI/Controllers/GerbilsController.cs
2023-10-21 14:02:51 +02:00

95 lines
2.7 KiB
C#

using GerbilManager.Models;
using GerbilManager.Repositories;
using GerbilManager.Dtos;
using Microsoft.AspNetCore.Mvc;
using GerbilManager.Converter;
namespace GerbilManager.Controllers
{
[ApiController]
[Route("gerbils")]
public class GerbilsController : ControllerBase
{
private readonly IGerbilRepository repository;
private readonly IBreederRepository breederRepository;
private readonly ILitterRepository litterRepository;
public GerbilsController(IGerbilRepository repo)
{
this.repository = repo;
}
//GET /gerbils
[HttpGet]
public IEnumerable<GerbilDto> GetGerbils()
{
var items = repository.GetGerbils().Select( gerbil => gerbil.AsDto());
return items;
}
//GET /gerbils
[HttpGet("{id}")]
public ActionResult<GerbilDto> GetGerbil(Guid id)
{
var item = repository.GetGerbil(id).AsDto();
if(item is null)
{
return NotFound();
}
return item;
}
[HttpPost()]
public ActionResult<GerbilDto> CreateGerbil(CreateGerbilDto dto)
{
Gerbil gerbil = new Gerbil{
Id = Guid.NewGuid(),
Name = dto.Name,
Breeder = breederRepository.GetBreeder(dto.Breeder),
Litter = litterRepository.GetLitter(dto.Litter),
Gender = (Gender) (int) dto.Gender
};
this.repository.CreateGerbil(gerbil);
return CreatedAtAction(nameof(GetGerbil), new { id = gerbil.Id}, gerbil.AsDto());
}
[HttpPut("{id}")]
public ActionResult UpdateGerbil(Guid id, UpdateGerbilDto gerbilDto)
{
var existingItem = repository.GetGerbil(id);
if(existingItem is null)
{
return NotFound();
}
Gerbil updatedGerbil = existingItem with{
Breeder = breederRepository.GetBreeder(gerbilDto.Breeder.Id),
Litter = litterRepository.GetLitter(gerbilDto.Litter.Id),
Gender = (Gender) (int) gerbilDto.Gender,
Name = gerbilDto.Name
};
repository.UpdateGerbil(updatedGerbil);
return NoContent();
}
[HttpDelete("{id}")]
public ActionResult DeleteGerbil(Guid id)
{
var existingGerbil = repository.GetGerbil(id);
if(existingGerbil is null)
{
return NotFound();
}
repository.DeleteGerbil(existingGerbil);
return NoContent();
}
}
}