ProductService.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using Products.Business.Domain;
  2. using Products.Business.Repository;
  3. using Products.Common.Dtos;
  4. using Products.Common.Exceptions;
  5. namespace Products.Business.Service;
  6. public class ProductService : IProductService
  7. {
  8. private readonly IProductRepository _productRepository;
  9. // Inject ProductRepository
  10. public ProductService(IProductRepository productRepository)
  11. {
  12. _productRepository = productRepository;
  13. }
  14. public IEnumerable<ProductDto> GetProducts()
  15. {
  16. var products = _productRepository.GetProducts();
  17. return products.Select(MapProductToProductDto!);
  18. }
  19. public ProductDto GetProduct(int id)
  20. {
  21. var product = _productRepository.GetProduct(id);
  22. if (product == null) throw new RecordNotFoundException("Product not found");
  23. return MapProductToProductDto(product);
  24. }
  25. public ProductDto AddProduct(CreateProductDto product)
  26. {
  27. var createdProduct = _productRepository.AddProduct(new Product
  28. {
  29. Name = product.Name,
  30. Color = product.Color,
  31. Brand = product.Brand
  32. });
  33. return MapProductToProductDto(createdProduct);
  34. }
  35. public ProductDto UpdateProduct(int id, UpdateProductDto productDto)
  36. {
  37. var product = _productRepository.GetProduct(id);
  38. if (product == null) throw new RecordNotFoundException("Product not found");
  39. product.Name = productDto.Name;
  40. product.Color = productDto.Color;
  41. product.Brand = productDto.Brand;
  42. _productRepository.UpdateProduct(product);
  43. return GetProduct(id);
  44. }
  45. public void DeleteProduct(int id)
  46. {
  47. if (!_productRepository.ProductExists(id)) throw new RecordNotFoundException("Product not found");
  48. _productRepository.DeleteProduct(id);
  49. }
  50. // TODO: This can be avoided using AutoMapper, also this should not be in this class
  51. private ProductDto MapProductToProductDto(Product product)
  52. {
  53. return new ProductDto(
  54. product.Name,
  55. product.Color.ToString(),
  56. product.Brand,
  57. product.Id
  58. );
  59. }
  60. }