CourseWork_Borschevskaya_A..../Hospital/HospitalRestApi/Controllers/RecipeController.cs

114 lines
3.3 KiB
C#

using HospitalContracts.BindingModels;
using HospitalContracts.BusinessLogicContracts;
using HospitalContracts.SearchModels;
using HospitalContracts.ViewModels;
using HospitalDataModels.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace HospitalRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class RecipeController : ControllerBase
{
private readonly ILogger _logger;
private readonly IRecipeLogic _logic;
private readonly IMedicineLogic _logicM;
public RecipeController(IRecipeLogic logic, ILogger<RecipeController> logger, IMedicineLogic logicM)
{
_logger = logger;
_logic = logic;
_logicM = logicM;
}
[HttpGet]
public List<RecipeViewModel>? GetRecipes(int apothecaryid)
{
try
{
return _logic.ReadList(new RecipeSearchModel
{
ApothecaryId = apothecaryid
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка рецептов аптекаря id ={ Id}", apothecaryid);
throw;
}
}
[HttpGet]
public RecipeViewModel? GetRecipe(int id)
{
try
{
return _logic.ReadElement(new RecipeSearchModel
{
Id = id
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения рецепта ");
throw;
}
}
[HttpPost]
public void Create(RecipeBindingModel model)
{
try
{
_logic.Create(GetModelWithMedicines(model));
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания рецепта");
throw;
}
}
[HttpPost]
public void Update(RecipeBindingModel model)
{
try
{
_logic.Update(GetModelWithMedicines(model));
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления рецепта");
throw;
}
}
[HttpPost]
public void Delete(RecipeBindingModel model)
{
try
{
_logic.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления рецепта");
throw;
}
}
private RecipeBindingModel GetModelWithMedicines(RecipeBindingModel model)
{
var medicines = _logicM.ReadList(new MedicineSearchModel { Ids = model.RecipeMedicines.Keys.ToArray() });
if (medicines != null)
{
model.RecipeMedicines = medicines.Where(m => model.RecipeMedicines.Keys.Contains(m.Id))
.ToDictionary(m => m.Id, m => m as IMedicineModel);
}
return model;
}
}
}