File tree Expand file tree Collapse file tree 3 files changed +43
-5
lines changed
src/main/java/com/amigoscode/product Expand file tree Collapse file tree 3 files changed +43
-5
lines changed Original file line number Diff line number Diff line change @@ -16,12 +16,12 @@ public ProductController(ProductService productService) {
1616 }
1717
1818 @ GetMapping
19- public List <Product > getAllProducts () {
19+ public List <ProductResponse > getAllProducts () {
2020 return productService .getAllProducts ();
2121 }
2222
2323 @ GetMapping ("{id}" )
24- public Product getProductById (@ PathVariable ("id" ) UUID id ) {
24+ public ProductResponse getProductById (@ PathVariable ("id" ) UUID id ) {
2525 return productService .getProductById (id );
2626 }
2727
Original file line number Diff line number Diff line change 1+ package com .amigoscode .product ;
2+
3+ import java .math .BigDecimal ;
4+ import java .time .Instant ;
5+ import java .util .UUID ;
6+
7+ public record ProductResponse (
8+ UUID id ,
9+ String name ,
10+ String description ,
11+ BigDecimal price ,
12+ String imageUrl ,
13+ Integer stockLevel ,
14+ Instant createdAt ,
15+ Instant updatedAt ,
16+ Instant deletedAt
17+ ) {
18+ }
Original file line number Diff line number Diff line change 55
66import java .util .List ;
77import java .util .UUID ;
8+ import java .util .function .Function ;
9+ import java .util .stream .Collectors ;
810
911@ Service
1012public class ProductService {
@@ -14,12 +16,15 @@ public ProductService(ProductRepository productRepository) {
1416 this .productRepository = productRepository ;
1517 }
1618
17- public List <Product > getAllProducts () {
18- return productRepository .findAll ();
19+ public List <ProductResponse > getAllProducts () {
20+ return productRepository .findAll ().stream ()
21+ .map (mapToResponse ())
22+ .collect (Collectors .toList ());
1923 }
2024
21- public Product getProductById (UUID id ) {
25+ public ProductResponse getProductById (UUID id ) {
2226 return productRepository .findById (id )
27+ .map (mapToResponse ())
2328 .orElseThrow (() -> new ResourceNotFound (
2429 "product with id [" + id + "] not found"
2530 ));
@@ -48,4 +53,19 @@ public UUID saveNewProduct(NewProductRequest product) {
4853 productRepository .save (newProduct );
4954 return id ;
5055 }
56+
57+ private Function <Product , ProductResponse > mapToResponse () {
58+ return p -> new ProductResponse (
59+ p .getId (),
60+ p .getName (),
61+ p .getDescription (),
62+ p .getPrice (),
63+ p .getImageUrl (),
64+ p .getStockLevel (),
65+ p .getCreatedAt (),
66+ p .getUpdatedAt (),
67+ p .getDeletedAt ()
68+ );
69+ }
70+
5171}
You can’t perform that action at this time.
0 commit comments