simple-lis/Controllers/ObservationsController.cs
2024-12-13 18:17:45 +05:30

81 lines
2.5 KiB
C#

using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using SimpleLIS.DTO;
using SimpleLIS.Models;
using SimpleLIS.Services;
namespace SimpleLIS.Controllers;
[ApiController]
[Route("api/observations")]
public class ObservationsController : ControllerBase
{
private readonly ObservationService _observationService;
private readonly IMapper _mapper;
public ObservationsController(ObservationService observationService, IMapper mapper)
{
_observationService = observationService;
_mapper = mapper;
}
[HttpPost]
public async Task<IActionResult> CreateObservation([FromBody] ObservationDTO observationDto)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
var observation = _mapper.Map<Observation>(observationDto);
var createdObservation = await _observationService.CreateObservationAsync(observation);
var createdObservationDto = _mapper.Map<ObservationDTO>(createdObservation);
return Ok(createdObservationDto);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetObservation(int id)
{
var observation = await _observationService.GetObservationByIdAsync(id);
if (observation == null) return NotFound();
var observationDto = _mapper.Map<ObservationDTO>(observation);
return Ok(observationDto);
}
[HttpGet]
public async Task<IActionResult> ListObservations()
{
var observations = await _observationService.ListObservationsAsync();
var observationsDto = _mapper.Map<IEnumerable<ObservationDTO>>(observations);
return Ok(observationsDto);
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateObservation(int id, [FromBody] ObservationDTO observationDto)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
if (!await _observationService.ObservationExistsAsync(id))
{
return NotFound();
}
var observation = _mapper.Map<Observation>(observationDto);
observation.ObservationId = id;
var updatedObservation = await _observationService.UpdateObservationAsync(observation);
var updatedObservationDto = _mapper.Map<ObservationDTO>(updatedObservation);
return Ok(updatedObservationDto);
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteObservation(int id)
{
var deleted = await _observationService.DeleteObservationAsync(id);
if (!deleted) return NotFound();
return NoContent();
}
}