|
| 1 | +package com.mayank.catalog_service.domain; |
| 2 | + |
| 3 | +import com.mayank.catalog_service.ApplicationProperties; |
| 4 | +import jakarta.transaction.Transactional; |
| 5 | +import org.springframework.data.domain.Page; |
| 6 | +import org.springframework.data.domain.PageRequest; |
| 7 | +import org.springframework.data.domain.Pageable; |
| 8 | +import org.springframework.data.domain.Sort; |
| 9 | +import org.springframework.stereotype.Service; |
| 10 | + |
| 11 | +@Service |
| 12 | +@Transactional |
| 13 | +public class ProductService |
| 14 | +{ |
| 15 | + private final ProductRepository productRepository; |
| 16 | + private final ApplicationProperties applicationProperties; |
| 17 | + |
| 18 | + public ProductService(ProductRepository productRepository, ApplicationProperties applicationProperties) { |
| 19 | + this.productRepository = productRepository; |
| 20 | + this.applicationProperties = applicationProperties; |
| 21 | + } |
| 22 | + |
| 23 | + public PagedResult<Product> getProducts(int pageNo) |
| 24 | + { |
| 25 | + Sort sort = Sort.by("name").ascending(); |
| 26 | + pageNo = pageNo <= 1 ? 0 : pageNo - 1; |
| 27 | + Pageable pageable = PageRequest.of(pageNo, applicationProperties.pageSize(), sort); |
| 28 | + Page<Product> productsPage = productRepository.findAll(pageable).map(ProductMapper::toProduct); |
| 29 | + |
| 30 | + return new PagedResult<>( |
| 31 | + productsPage.getContent(), |
| 32 | + productsPage.getTotalElements(), |
| 33 | + productsPage.getNumber() + 1, |
| 34 | + productsPage.getTotalPages(), |
| 35 | + productsPage.isFirst(), |
| 36 | + productsPage.isLast(), |
| 37 | + productsPage.hasNext(), |
| 38 | + productsPage.hasPrevious() |
| 39 | + ); |
| 40 | + } |
| 41 | +} |
0 commit comments