ProductService.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using Microsoft.AspNetCore.JsonPatch;
  2. using AutoMapper;
  3. using Products.Business.Domain;
  4. using Products.Business.Repository;
  5. using Products.Common.Dtos;
  6. using Products.Common.Exceptions;
  7. namespace Products.Business.Service;
  8. public class ProductService : IProductService
  9. {
  10. private readonly IProductRepository _productRepository;
  11. private readonly IMapper _mapper;
  12. // Inject ProductRepository and AutoMapper
  13. public ProductService(IProductRepository productRepository, IMapper mapper)
  14. {
  15. _productRepository = productRepository;
  16. _mapper = mapper;
  17. }
  18. public IEnumerable<ProductDto> GetProducts()
  19. {
  20. var products = _productRepository.GetProducts();
  21. return _mapper.Map<List<ProductDto>>(products);
  22. }
  23. public ProductDto GetProduct(int id)
  24. {
  25. var product = _productRepository.GetProduct(id);
  26. if (product == null) throw new RecordNotFoundException("Product not found");
  27. return _mapper.Map<ProductDto>(product);
  28. }
  29. public ProductDto AddProduct(CreateProductDto product)
  30. {
  31. var createdProduct = _productRepository.AddProduct(new Product
  32. {
  33. Name = product.Name,
  34. Color = product.Color,
  35. Brand = product.Brand
  36. });
  37. return _mapper.Map<ProductDto>(createdProduct);
  38. }
  39. public void DeleteProduct(int id)
  40. {
  41. if (!_productRepository.ProductExists(id)) throw new RecordNotFoundException("Product not found");
  42. _productRepository.DeleteProduct(id);
  43. }
  44. public ProductDto UpdateProduct(int id, UpdateProductDto productDto)
  45. {
  46. var product = _productRepository.GetProduct(id);
  47. if (product == null) throw new RecordNotFoundException("Product not found");
  48. product.Name = productDto.Name;
  49. product.Color = productDto.Color;
  50. product.Brand = productDto.Brand;
  51. _productRepository.UpdateProduct(product);
  52. return this.GetProduct(id);
  53. }
  54. public ProductDto PatchProduct(int id,
  55. JsonPatchDocument<UpdateProductDto> productDto)
  56. {
  57. var product = _productRepository.GetProduct(id);
  58. if (product == null) throw new RecordNotFoundException("Product not found");
  59. // Apply the patch
  60. var update = _mapper.Map<UpdateProductDto>(product);
  61. productDto.ApplyTo(update);
  62. // Update the product
  63. _mapper.Map(update, product);
  64. _productRepository.UpdateProduct(product);
  65. return this.GetProduct(id);
  66. }
  67. }