BuecherwurmAPI/Controllers/LendController.cs

92 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using BuecherwurmAPI.Models;
using BuecherwurmAPI.DTOs;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.Extensions.Logging;
using Microsoft.Data.Sqlite;
namespace BuecherwurmAPI.Controllers
{
[Route("api/leihvorgang")]
[ApiController]
public class LendController : ControllerBase
{
private readonly LendModel _repository;
private readonly IMapper _mapper;
public LendController(IModel repo, IMapper mapper)
{
_repository = (LendModel)repo;
_mapper = mapper;
}
//GET api/leihvorgang
[HttpGet]
public ActionResult<IEnumerable<Lend>> LendsGet()
{
return Ok(_repository.GetAllLends());
}
//POST api/leihvorgang
[HttpPost]
public ActionResult<LendReadDTO> LendsPost(LendSeed lend)
{
/*
Internally a lend is stored with an id
but the client shouldn't be allowed to set or change it
therefore the package 'AutoMapper' is used to prevent errors
that could happen when doing this task manually.
It takes the information from the client and maps it to the
corresponding internal object which then will be returned.
Furthermore it could be used to keep some attributes secret.
Another nice effect of this is that the implementation could be changed
while the interface could be retained by some minor changes in the code.
DTO stands for Data Transfer Object
*/
var newId = _repository.insertLendReturningId(lend);
if (newId > 0)
{
var item = new Lend
{
Id = newId,
Customer = lend.Customer,
Returned = false,
ItemId = lend.ItemId,
ReturnDate = lend.ReturnDate
};
return Ok(item);
}
else
{
return BadRequest();
}
//return Ok(_mapper.Map<LendReadDTO>(item));
}
//GET api/leihvorgang/{id}
[HttpGet("{id}")]
public ActionResult<Lend> LendById(long id)
{
var lend = _repository.GetLendById(id);
if (!_repository.IdExits(Tables.Table.Lends, id))
{
return NotFound();
}
return Ok(lend);
}
//PATCH api/leihvorgang/{id}
[HttpPatch("{id}")]
public ActionResult LendPatchById(int id, JsonPatchDocument<Lend> patchDocument)
{
return Ok();
}
}
}