Add order history endpoint
Problem Context
The team needs to add an endpoint that returns all orders for a user, including the products in each order. This will be displayed on the 'My Orders' page.
Intermediate
100 points
File Changes (1)
src/main/java/com/example/service/OrderService.java
MODIFIED
@@ -25 +25 @@
| 25 | 25 | @Service |
| 26 | 26 | @RequiredArgsConstructor |
| 27 | 27 | public class OrderService { |
| 28 | 28 | private final OrderRepository orderRepository; |
| 29 | 29 | private final ProductRepository productRepository; |
| 30 | + |
|
| 31 | + public List<OrderDTO> getUserOrderHistory(Long userId) { |
|
| 32 | + List<Order> orders = orderRepository.findByUserId(userId); |
|
| 33 | + List<OrderDTO> result = new ArrayList<>(); |
|
| 34 | + |
|
| 35 | + for (Order order : orders) { |
|
| 36 | + OrderDTO dto = new OrderDTO(); |
|
| 37 | + dto.setOrderId(order.getId()); |
|
| 38 | + dto.setOrderDate(order.getCreatedAt()); |
|
| 39 | + |
|
| 40 | + // Get products for this order |
|
| 41 | + List<Product> products = productRepository.findByOrderId(order.getId()); |
|
| 42 | + dto.setProducts(products.stream() |
|
| 43 | + .map(this::toProductDTO) |
|
| 44 | + .collect(Collectors.toList())); |
|
| 45 | + |
|
| 46 | + result.add(dto); |
|
| 47 | + } |
|
| 48 | + return result; |
|
| 49 | + } |
|
| 30 | 50 | } |
Login Required: You must be registered to submit reviews and receive AI feedback.
Register or
login to start reviewing!
Your Review
Review Tips
- Look for security vulnerabilities (SQL injection, XSS, etc.)
- Check for null pointer exceptions and error handling
- Consider performance implications
- Evaluate code maintainability and readability
- Check for proper resource management
- Look for logic errors or edge cases