using AutoMapper; using CodeReviewApp.ConfiguringManager; using CodeReviewApp.Models; using DAL.Repositories; using Domain.Models; using Microsoft.AspNetCore.Mvc; namespace CodeReviewApp.Controllers; public class ProductController: ControllerBase { private readonly IProductRepository _productRepository; private readonly ILogger _logger; private readonly IMapper _mapper; public ProductController(IProductRepository productRepository, ILogger logger, IMapper mapper) { _productRepository = productRepository; _logger = logger; _mapper = mapper; } [HttpGet] public async Task GetAll() { _logger.LogInformation($"Api method {Request.Path.Value} was started"); var cts = new CancellationTokenSource(); var token = cts.Token; return Ok(await _productRepository.GetAll( Configurations.Redis.CacheLifeTime, token)); } [HttpPost("add")] public async Task Add([FromBody] ProductRequest productRequest) { _logger.LogInformation($"Api method {Request.Path.Value} was started"); if (!ModelState.IsValid) { _logger.LogWarning($"Api method {Request.Path.Value}, {ModelState}"); return BadRequest(ModelState); } var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(Configurations.Database.TimeOut)); var token = cts.Token; var entity = _mapper.Map(productRequest); try { await _productRepository.Create(entity, Configurations.Redis.CacheLifeTime, token); } catch (Exception ex) { _logger.LogError(ex, ex.Message); return StatusCode(500); } return Ok(); } [HttpGet("{id:int}")] public async Task GetById(int id) { _logger.LogInformation($"Api method {Request.Path.Value} was started"); var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(Configurations.Database.TimeOut)); var token = cts.Token; return Ok(await _productRepository.Get(id, Configurations.Redis.CacheLifeTime, token)); } [HttpPost("delete/{id:int}")] public async Task Delete(int id) { _logger.LogInformation($"Api method {Request.Path.Value} was started"); var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(Configurations.Database.TimeOut)); var token = cts.Token; try { await _productRepository.Delete(id, token); } catch (Exception ex) { _logger.LogError(ex, ex.Message); return StatusCode(500); } return Ok(); } [HttpPost("update")] public async Task Update([FromBody] Product productRequest) { _logger.LogInformation($"Api method {Request.Path.Value} was started"); if (!ModelState.IsValid) { _logger.LogWarning($"Api method {Request.Path.Value}, {ModelState}"); return BadRequest(ModelState); } var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(Configurations.Database.TimeOut)); var token = cts.Token; try { await _productRepository.Update(productRequest, Configurations.Redis.CacheLifeTime, token); } catch (Exception ex) { _logger.LogError(ex, ex.Message); return StatusCode(500); } return Ok(); } }