Skip to content

Commit d0ad718

Browse files
product-api: dto exercise sol
1 parent 1ce58fb commit d0ad718

File tree

3 files changed

+43
-5
lines changed

3 files changed

+43
-5
lines changed

src/main/java/com/amigoscode/product/ProductController.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff 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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
}

src/main/java/com/amigoscode/product/ProductService.java

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
import java.util.List;
77
import java.util.UUID;
8+
import java.util.function.Function;
9+
import java.util.stream.Collectors;
810

911
@Service
1012
public 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
}

0 commit comments

Comments
 (0)