110 lines
3.1 KiB
C#
110 lines
3.1 KiB
C#
using GerbilManagerWebAPI.Models;
|
|
using GerbilManagerWebAPI.DAL;
|
|
using GerbilManagerWebAPI.Dtos;
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using GerbilManagerWebAPI.Converter;
|
|
|
|
namespace GerbilManagerWebAPI.Controllers
|
|
{
|
|
[ApiController]
|
|
[Route("gerbils")]
|
|
public class GerbilsController : ControllerBase
|
|
{
|
|
private readonly UnitOfWork unitOfWork;
|
|
|
|
public GerbilsController(UnitOfWork unitOfWork)
|
|
{
|
|
this.unitOfWork = unitOfWork;
|
|
}
|
|
|
|
//GET /gerbils
|
|
[HttpGet]
|
|
public IEnumerable<GerbilDto> GetGerbils([FromQuery]string? name)
|
|
{
|
|
if(name != null)
|
|
{
|
|
return unitOfWork.GerbilRepository.Get(filter: x => x.Name == name).Select( gerbil => gerbil.AsDto());
|
|
}
|
|
|
|
var items = unitOfWork.GerbilRepository.Get().Select( gerbil => gerbil.AsDto());
|
|
return items;
|
|
}
|
|
|
|
//GET /gerbils
|
|
[HttpGet("{id}")]
|
|
public ActionResult<GerbilDto> GetGerbil(Guid id)
|
|
{
|
|
var item = unitOfWork.GerbilRepository.GetByID(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,
|
|
Gender = (Gender) (int) dto.Gender
|
|
};
|
|
|
|
if(dto.Litter != Guid.Empty)
|
|
{
|
|
gerbil.Litter = unitOfWork.LitterRepository.GetByID(dto.Litter);
|
|
}
|
|
|
|
if(dto.Breeder != Guid.Empty)
|
|
{
|
|
gerbil.Breeder = unitOfWork.BreederRepository.GetByID(dto.Breeder);
|
|
}
|
|
|
|
this.unitOfWork.GerbilRepository.Insert(gerbil);
|
|
this.unitOfWork.Save();
|
|
|
|
return CreatedAtAction(nameof(GetGerbil), new { id = gerbil.Id}, gerbil.AsDto());
|
|
}
|
|
|
|
[HttpPut("{id}")]
|
|
public ActionResult UpdateGerbil(Guid id, UpdateGerbilDto gerbilDto)
|
|
{
|
|
var existingItem = unitOfWork.GerbilRepository.GetByID(id);
|
|
if(existingItem is null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
Gerbil updatedGerbil = existingItem with{
|
|
Breeder = unitOfWork.BreederRepository.GetByID(gerbilDto.Breeder.Id),
|
|
Litter = unitOfWork.LitterRepository.GetByID(gerbilDto.Litter.Id),
|
|
Gender = (Gender) (int) gerbilDto.Gender,
|
|
Name = gerbilDto.Name
|
|
};
|
|
|
|
unitOfWork.GerbilRepository.Update(updatedGerbil);
|
|
this.unitOfWork.Save();
|
|
|
|
return NoContent();
|
|
}
|
|
|
|
[HttpDelete("{id}")]
|
|
public ActionResult DeleteGerbil(Guid id)
|
|
{
|
|
var existingGerbil = unitOfWork.GerbilRepository.GetByID(id);
|
|
|
|
if(existingGerbil is null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
unitOfWork.GerbilRepository.Delete(existingGerbil);
|
|
this.unitOfWork.Save();
|
|
|
|
return NoContent();
|
|
}
|
|
}
|
|
} |