Skip to content

Commit 5d5bd1e

Browse files
product-api: delete by id sol
1 parent 30cd472 commit 5d5bd1e

File tree

4 files changed

+30
-1
lines changed

4 files changed

+30
-1
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.amigoscode.exception;
2+
3+
import org.springframework.http.HttpStatus;
4+
import org.springframework.web.bind.annotation.ResponseStatus;
5+
6+
@ResponseStatus(HttpStatus.NOT_FOUND)
7+
public class ResourceNotFound extends RuntimeException {
8+
public ResourceNotFound(String message) {
9+
super(message);
10+
}
11+
}

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package com.amigoscode.product;
22

33
import org.springframework.web.bind.annotation.GetMapping;
4+
import org.springframework.web.bind.annotation.PathVariable;
45
import org.springframework.web.bind.annotation.RequestMapping;
56
import org.springframework.web.bind.annotation.RestController;
67

78
import java.util.List;
9+
import java.util.UUID;
810

911
@RestController
1012
@RequestMapping("/api/v1/products")
@@ -20,4 +22,9 @@ public ProductController(ProductService productService) {
2022
public List<Product> getAllProducts() {
2123
return productService.getAllProducts();
2224
}
25+
26+
@GetMapping("{id}")
27+
public Product getProductById(@PathVariable("id") UUID id) {
28+
return productService.getProductById(id);
29+
}
2330
}

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package com.amigoscode.product;
22

3+
import com.amigoscode.exception.ResourceNotFound;
34
import org.springframework.stereotype.Service;
45

56
import java.util.List;
7+
import java.util.UUID;
68

79
@Service
810
public class ProductService {
@@ -15,4 +17,11 @@ public ProductService(ProductRepository productRepository) {
1517
public List<Product> getAllProducts() {
1618
return productRepository.findAll();
1719
}
20+
21+
public Product getProductById(UUID id) {
22+
return productRepository.findById(id)
23+
.orElseThrow(() -> new ResourceNotFound(
24+
"product with id [" + id + "] not found"
25+
));
26+
}
1827
}

src/main/resources/application.properties

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,6 @@ spring.datasource.driver-class-name=org.postgresql.Driver
66

77
spring.jpa.hibernate.ddl-auto=create-drop
88
spring.jpa.show-sql=true
9-
spring.jpa.properties.hibernate.format_sql=true
9+
spring.jpa.properties.hibernate.format_sql=true
10+
11+
server.error.include-message=always

0 commit comments

Comments
 (0)