Conversation
Cart 도메인으로 로직 이동 및 수정
Walkthrough이번 변경 사항은 MongoDB 연동을 위한 의존성 추가와 함께 Spring Boot 애플리케이션에 MongoClient 및 MongoDatabase 빈을 등록하는 작업을 포함합니다. 또한, 카트와 관련된 도메인, 서비스, 컨트롤러, DTO, 저장소(repository) 클래스가 새롭게 추가되거나 수정되었으며, 각 기능에 대한 단위 테스트도 함께 도입되었습니다. Changes
Sequence Diagram(s)sequenceDiagram
participant U as 사용자
participant LIC as LineItemController
participant CS as CartService
participant PR as ProductRepository
participant CR as CartRepository
U->>LIC: POST /cart/line-items (AddProductToCartDto)
LIC->>CS: addProduct(productId, quantity)
CS->>PR: find(productId)
PR-->>CS: Product 정보 반환
CS->>CR: getCart()로 기존 카트 조회
CS->>CR: save(cart)로 카트 저장
CS-->>LIC: 처리 결과 반환
LIC-->>U: HTTP 200 응답 전송
Poem
✨ Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 13
🧹 Nitpick comments (11)
src/main/java/com/example/demo/controllers/dtos/CartDto.java (1)
1-19: DTO 구조가 간결하고 일관적입니다.
CartDto와 내부LineItemDto를 통해 장바구니와 해당 품목 정보를 명확하게 표현하고 있습니다.
금액 정보를 다룰 때는 필요에 따라BigDecimal등을 고려해 정밀도 손실을 방지하는 방법도 검토할 수 있습니다.src/main/java/com/example/demo/infrastructure/CartRepository.java (1)
18-21: find 메서드에 예외 처리를 추가하세요.데이터베이스 조회 시 발생할 수 있는 예외에 대한 처리가 필요합니다.
다음과 같이 수정하는 것을 제안합니다:
public Cart find() { + try { List<LineItem> lineItems = lineItemRepository.findAll(); return new Cart(lineItems); + } catch (Exception e) { + throw new RuntimeException("장바구니 조회 중 오류가 발생했습니다.", e); + } }src/test/java/com/example/demo/model/LineItemTest.java (2)
17-29: 테스트 케이스 보완 필요현재 구현된
addQuantity테스트는 기본적인 시나리오만 검증하고 있습니다. 다음과 같은 추가 테스트 케이스를 고려해 주세요:
- 음수 수량 추가 시의 동작
- 최대 허용 수량 초과 시의 동작
- 0 수량 추가 시의 동작
31-42: 상품 설정 관련 예외 케이스 테스트 필요
setProductAndGetTotalPrice테스트에 다음 시나리오를 추가하는 것이 좋습니다:
- null 상품 설정 시의 동작
- 상품 정보가 없는 경우의 동작
- 가격이 0인 상품의 총액 계산
src/main/java/com/example/demo/model/Cart.java (1)
38-43: Null 반환 대신 Optional 사용 권장
getLineItem메서드에서 null을 반환하는 대신 Optional을 사용하는 것이 더 안전한 방식입니다.-public LineItem getLineItem(Product product) { +public Optional<LineItem> getLineItem(Product product) { return lineItems.stream() .filter(i -> i.getProductId().equals(product.getId())) - .findFirst() - .orElse(null); + .findFirst(); }src/main/java/com/example/demo/application/CartService.java (1)
46-54: 메서드 문서화가 필요합니다.공개 메서드에 대한 JavaDoc 문서화를 추가하면 좋겠습니다.
다음과 같이 문서화를 추가하는 것을 제안합니다:
+ /** + * 장바구니에 상품을 추가합니다. + * @param productId 추가할 상품의 ID + * @param quantity 추가할 상품의 수량 + * @throws ProductNotFoundException 상품을 찾을 수 없는 경우 + */ public void addProduct(String productId, int quantity) {src/test/java/com/example/demo/application/CartServiceTest.java (1)
53-63: 테스트 케이스 보완이 필요합니다.현재는 기본적인 상품 추가 케이스만 테스트하고 있습니다. 다음과 같은 추가 테스트 케이스가 필요합니다:
- 존재하지 않는 상품 ID로 추가 시도
- 음수 수량으로 추가 시도
- 재고보다 많은 수량으로 추가 시도
src/test/java/com/example/demo/controllers/LineItemControllerTest.java (2)
39-53: 유효성 검사 테스트가 잘 구현되었습니다.빈 productId에 대한 검증 테스트가 적절히 구현되어 있습니다. 다만, 다음 사항을 고려해보시기 바랍니다:
- null 값에 대한 테스트 케이스 추가
- 최대 길이 제한에 대한 테스트 케이스 추가
55-69: 수량 검증 테스트가 잘 구현되었습니다.수량이 0일 때의 검증이 잘 구현되어 있습니다. 추가로 다음 테스트 케이스도 고려해보시면 좋겠습니다:
- 음수 수량에 대한 테스트
- 최대 허용 수량 초과에 대한 테스트
src/test/java/com/example/demo/model/CartTest.java (1)
107-111: 헬퍼 메서드 구현이 적절합니다만, 개선의 여지가 있습니다.createLineItem 메서드가 테스트 코드 중복을 잘 제거하고 있습니다. 다만 다음과 같은 개선을 고려해보세요:
- 빌더 패턴 적용
- 메서드 접근 제어자를 private static으로 변경
- private LineItem createLineItem(Product product, int quantity) { + private static LineItem createLineItem(Product product, int quantity) { LineItem lineItem = new LineItem(product.getId(), quantity); lineItem.setProduct(product); return lineItem; }build.gradle.kts (1)
22-23: MongoDB 드라이버 의존성이 추가되었습니다.MongoDB 드라이버 의존성이 잘 추가되었습니다만, 다음 사항들을 고려해보시기 바랍니다:
- 버전을 변수로 추출하여 관리
- Spring Data MongoDB 사용 고려
+ val mongoDriverVersion = "5.3.1" - implementation("org.mongodb:mongodb-driver-core:5.3.1") - implementation("org.mongodb:mongodb-driver-sync:5.3.1") + implementation("org.mongodb:mongodb-driver-core:${mongoDriverVersion}") + implementation("org.mongodb:mongodb-driver-sync:${mongoDriverVersion}")또는 Spring Data MongoDB를 사용하는 것을 고려해보세요:
+ implementation("org.springframework.boot:spring-boot-starter-data-mongodb") - implementation("org.mongodb:mongodb-driver-core:5.3.1") - implementation("org.mongodb:mongodb-driver-sync:5.3.1")
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (19)
build.gradle.kts(1 hunks)src/main/java/com/example/demo/Application.java(1 hunks)src/main/java/com/example/demo/application/CartService.java(1 hunks)src/main/java/com/example/demo/controllers/CartController.java(1 hunks)src/main/java/com/example/demo/controllers/LineItemController.java(1 hunks)src/main/java/com/example/demo/controllers/dtos/AddProductToCartDto.java(1 hunks)src/main/java/com/example/demo/controllers/dtos/CartDto.java(1 hunks)src/main/java/com/example/demo/infrastructure/CartRepository.java(1 hunks)src/main/java/com/example/demo/infrastructure/LineItemRepository.java(1 hunks)src/main/java/com/example/demo/infrastructure/ProductRepository.java(1 hunks)src/main/java/com/example/demo/model/Cart.java(1 hunks)src/main/java/com/example/demo/model/LineItem.java(1 hunks)src/main/java/com/example/demo/model/Product.java(1 hunks)src/test/java/com/example/demo/MongoTest.java(1 hunks)src/test/java/com/example/demo/application/CartServiceTest.java(1 hunks)src/test/java/com/example/demo/controllers/CartControllerTest.java(1 hunks)src/test/java/com/example/demo/controllers/LineItemControllerTest.java(3 hunks)src/test/java/com/example/demo/model/CartTest.java(1 hunks)src/test/java/com/example/demo/model/LineItemTest.java(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- src/main/java/com/example/demo/model/Product.java
🔇 Additional comments (9)
src/main/java/com/example/demo/controllers/CartController.java (4)
3-7: 의존성 주입 및 DTO 임포트가 잘 이루어졌습니다.
Spring Boot 애플리케이션의 계층 구조에 맞춰 필요한 의존성과 DTO를 깔끔하게 불러오고 있습니다.
16-20: 생성자 주입 방식이 적절합니다.
스프링에서 권장하는 생성자 주입 방식을 잘 활용하여CartService를 주입하고 있습니다.
23-31: 장바구니 상세 정보 반환 로직 검증
Cart객체에서LineItem리스트를 DTO로 변환해CartDto에 담아 반환하는 로직이 직관적이며 데이터 흐름이 명확합니다.
단,cart.getLineItems()가 null일 가능성이 전혀 없다면 괜찮으나, 혹시 모를 예외 상황을 고려해 방어적 코드를 추가하는 것도 좋습니다.
33-40: LineItem 매핑 로직이 깔끔합니다.
LineItem의 필드를 그대로CartDto.LineItemDto로 매핑하여 DTO 구조를 명료하게 유지하고 있습니다.src/main/java/com/example/demo/controllers/dtos/AddProductToCartDto.java (1)
1-13: 필드 유효성 검증이 적절합니다.
@NotBlank와@Positive애너테이션을 사용해productId와quantity의 유효 범위를 명확하게 설정하였으며, 입력 데이터 무결성을 보장하기에 적합합니다.src/test/java/com/example/demo/controllers/CartControllerTest.java (1)
26-39: 테스트 구현이 잘 되었습니다!CartService를 모킹하고 기본 장바구니 응답을 검증하는 테스트가 잘 구현되어 있습니다.
src/test/java/com/example/demo/controllers/LineItemControllerTest.java (1)
20-21: CartService 모의 객체가 적절히 추가되었습니다.CartService를 @MockBean으로 주입하여 테스트 격리성을 잘 유지하고 있습니다.
src/test/java/com/example/demo/model/CartTest.java (2)
16-20: 테스트 설정이 깔끔하게 구현되었습니다.@beforeeach를 사용하여 테스트 데이터를 적절히 초기화하고 있습니다.
22-28: 빈 카트 테스트가 잘 구현되었습니다.빈 카트의 총액이 0원인지 확인하는 기본 테스트가 잘 구현되어 있습니다.
| @Bean | ||
| public MongoClient mongoClient() { | ||
| return MongoClients.create("mongodb://localhost:27017"); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
MongoDB 연결 설정을 외부 구성으로 이동하세요.
하드코딩된 MongoDB 연결 문자열을 application.properties 또는 application.yml로 이동하여 환경별로 구성을 관리하는 것이 좋습니다.
다음과 같이 수정하는 것을 제안합니다:
+@Value("${spring.data.mongodb.uri}")
+private String mongoUri;
@Bean
public MongoClient mongoClient() {
- return MongoClients.create("mongodb://localhost:27017");
+ return MongoClients.create(mongoUri);
}그리고 application.yml에 다음을 추가하세요:
spring:
data:
mongodb:
uri: mongodb://localhost:27017| @Bean | ||
| public MongoDatabase mongoDatabase(MongoClient mongoClient) { | ||
| return mongoClient.getDatabase("demo"); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
데이터베이스 이름도 구성 파일로 이동하세요.
데이터베이스 이름도 외부 구성으로 관리하면 환경별로 다른 데이터베이스를 사용할 수 있습니다.
다음과 같이 수정하는 것을 제안합니다:
+@Value("${spring.data.mongodb.database}")
+private String databaseName;
@Bean
public MongoDatabase mongoDatabase(MongoClient mongoClient) {
- return mongoClient.getDatabase("demo");
+ return mongoClient.getDatabase(databaseName);
}그리고 application.yml에 다음을 추가하세요:
spring:
data:
mongodb:
database: demo| public void save(Cart cart) { | ||
| cart.getLineItems().forEach(lineItem -> { | ||
| if (lineItem.getId() == null) { | ||
| lineItemRepository.add(lineItem); | ||
| } | ||
| lineItemRepository.update(lineItem); | ||
| }); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
save 메서드의 로직을 개선하세요.
현재 구현에서는 모든 LineItem에 대해 불필요한 update가 수행될 수 있습니다. 또한 예외 처리가 누락되어 있습니다.
다음과 같이 개선하는 것을 제안합니다:
public void save(Cart cart) {
+ try {
cart.getLineItems().forEach(lineItem -> {
if (lineItem.getId() == null) {
lineItemRepository.add(lineItem);
+ } else {
+ lineItemRepository.update(lineItem);
}
- lineItemRepository.update(lineItem);
});
+ } catch (Exception e) {
+ throw new RuntimeException("장바구니 저장 중 오류가 발생했습니다.", e);
+ }
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public void save(Cart cart) { | |
| cart.getLineItems().forEach(lineItem -> { | |
| if (lineItem.getId() == null) { | |
| lineItemRepository.add(lineItem); | |
| } | |
| lineItemRepository.update(lineItem); | |
| }); | |
| } | |
| public void save(Cart cart) { | |
| try { | |
| cart.getLineItems().forEach(lineItem -> { | |
| if (lineItem.getId() == null) { | |
| lineItemRepository.add(lineItem); | |
| } else { | |
| lineItemRepository.update(lineItem); | |
| } | |
| }); | |
| } catch (Exception e) { | |
| throw new RuntimeException("장바구니 저장 중 오류가 발생했습니다.", e); | |
| } | |
| } |
| @Test | ||
| void test() { | ||
|
|
||
| MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); | ||
| MongoDatabase database = mongoClient.getDatabase("demo"); | ||
| MongoCollection<Document> collection = database.getCollection("products"); | ||
|
|
||
| List<Document> documents = new ArrayList<>(); | ||
| collection.find().into(documents); | ||
|
|
||
| assertThat(documents.get(0).getString("name")).isEqualTo("티셔츠"); | ||
| assertThat(documents.get(1).getString("name")).isEqualTo("청바지"); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
테스트 코드의 안정성을 개선하세요.
현재 테스트는 데이터베이스에 특정 데이터가 존재한다고 가정하고 있어 불안정할 수 있습니다. 또한 테스트 후 정리(cleanup)가 누락되어 있습니다.
다음과 같이 개선하는 것을 제안합니다:
+@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MongoTest {
+ private MongoClient mongoClient;
+ private MongoDatabase database;
+ private MongoCollection<Document> collection;
+ @BeforeAll
+ void setUp() {
+ mongoClient = MongoClients.create("mongodb://localhost:27017");
+ database = mongoClient.getDatabase("demo");
+ collection = database.getCollection("products");
+ }
+ @BeforeEach
+ void prepare() {
+ // 테스트 데이터 설정
+ collection.insertMany(Arrays.asList(
+ new Document("name", "티셔츠"),
+ new Document("name", "청바지")
+ ));
+ }
+ @AfterEach
+ void cleanup() {
+ collection.deleteMany(new Document());
+ }
+ @AfterAll
+ void tearDown() {
+ mongoClient.close();
+ }
@Test
void test() {
- MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
- MongoDatabase database = mongoClient.getDatabase("demo");
- MongoCollection<Document> collection = database.getCollection("products");
List<Document> documents = new ArrayList<>();
collection.find().into(documents);
assertThat(documents.get(0).getString("name")).isEqualTo("티셔츠");
assertThat(documents.get(1).getString("name")).isEqualTo("청바지");
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| @Test | |
| void test() { | |
| MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); | |
| MongoDatabase database = mongoClient.getDatabase("demo"); | |
| MongoCollection<Document> collection = database.getCollection("products"); | |
| List<Document> documents = new ArrayList<>(); | |
| collection.find().into(documents); | |
| assertThat(documents.get(0).getString("name")).isEqualTo("티셔츠"); | |
| assertThat(documents.get(1).getString("name")).isEqualTo("청바지"); | |
| } | |
| @TestInstance(TestInstance.Lifecycle.PER_CLASS) | |
| public class MongoTest { | |
| private MongoClient mongoClient; | |
| private MongoDatabase database; | |
| private MongoCollection<Document> collection; | |
| @BeforeAll | |
| void setUp() { | |
| mongoClient = MongoClients.create("mongodb://localhost:27017"); | |
| database = mongoClient.getDatabase("demo"); | |
| collection = database.getCollection("products"); | |
| } | |
| @BeforeEach | |
| void prepare() { | |
| // 테스트 데이터 설정 | |
| collection.insertMany(Arrays.asList( | |
| new Document("name", "티셔츠"), | |
| new Document("name", "청바지") | |
| )); | |
| } | |
| @AfterEach | |
| void cleanup() { | |
| collection.deleteMany(new Document()); | |
| } | |
| @AfterAll | |
| void tearDown() { | |
| mongoClient.close(); | |
| } | |
| @Test | |
| void test() { | |
| List<Document> documents = new ArrayList<>(); | |
| collection.find().into(documents); | |
| assertThat(documents.get(0).getString("name")).isEqualTo("티셔츠"); | |
| assertThat(documents.get(1).getString("name")).isEqualTo("청바지"); | |
| } | |
| } |
| @PostMapping | ||
| @ResponseStatus(HttpStatus.CREATED) | ||
| void create() { | ||
| // | ||
| void create( | ||
| @Valid @RequestBody AddProductToCartDto addProductToCartDto | ||
| ) { | ||
| cartService.addProduct( | ||
| addProductToCartDto.productId(), | ||
| addProductToCartDto.quantity() | ||
| ); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
API 응답 처리를 개선하세요.
현재 구현에서는 생성된 리소스에 대한 정보를 반환하지 않으며, 오류 처리도 누락되어 있습니다.
다음과 같이 개선하는 것을 제안합니다:
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
-void create(
+LineItemResponse create(
@Valid @RequestBody AddProductToCartDto addProductToCartDto
) {
+ try {
- cartService.addProduct(
+ LineItem lineItem = cartService.addProduct(
addProductToCartDto.productId(),
addProductToCartDto.quantity()
);
+ return LineItemResponse.from(lineItem);
+ } catch (ProductNotFoundException e) {
+ throw new ResponseStatusException(HttpStatus.NOT_FOUND, "상품을 찾을 수 없습니다.");
+ } catch (Exception e) {
+ throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "장바구니에 상품을 추가하는 중 오류가 발생했습니다.");
+ }
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| @PostMapping | |
| @ResponseStatus(HttpStatus.CREATED) | |
| void create() { | |
| // | |
| void create( | |
| @Valid @RequestBody AddProductToCartDto addProductToCartDto | |
| ) { | |
| cartService.addProduct( | |
| addProductToCartDto.productId(), | |
| addProductToCartDto.quantity() | |
| ); | |
| } | |
| @PostMapping | |
| @ResponseStatus(HttpStatus.CREATED) | |
| LineItemResponse create( | |
| @Valid @RequestBody AddProductToCartDto addProductToCartDto | |
| ) { | |
| try { | |
| LineItem lineItem = cartService.addProduct( | |
| addProductToCartDto.productId(), | |
| addProductToCartDto.quantity() | |
| ); | |
| return LineItemResponse.from(lineItem); | |
| } catch (ProductNotFoundException e) { | |
| throw new ResponseStatusException(HttpStatus.NOT_FOUND, "상품을 찾을 수 없습니다."); | |
| } catch (Exception e) { | |
| throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "장바구니에 상품을 추가하는 중 오류가 발생했습니다."); | |
| } | |
| } |
| public void setProduct(Product product) { | ||
| this.productName = product.getName(); | ||
| this.unitPrice = product.getPrice(); | ||
| } |
There was a problem hiding this comment.
상품 설정 시 검증 로직 필요
setProduct 메서드에서 null 상품에 대한 검증이 필요합니다.
public void setProduct(Product product) {
+ if (product == null) {
+ throw new IllegalArgumentException("상품이 null일 수 없습니다.");
+ }
this.productName = product.getName();
this.unitPrice = product.getPrice();
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public void setProduct(Product product) { | |
| this.productName = product.getName(); | |
| this.unitPrice = product.getPrice(); | |
| } | |
| public void setProduct(Product product) { | |
| if (product == null) { | |
| throw new IllegalArgumentException("상품이 null일 수 없습니다."); | |
| } | |
| this.productName = product.getName(); | |
| this.unitPrice = product.getPrice(); | |
| } |
| public void addQuantity(int quantity) { | ||
| this.quantity += quantity; | ||
| } |
There was a problem hiding this comment.
수량 추가 시 검증 로직 필요
addQuantity 메서드에서 음수 수량이나 최대 허용 수량 초과에 대한 검증이 필요합니다.
public void addQuantity(int quantity) {
+ if (quantity <= 0) {
+ throw new IllegalArgumentException("추가할 수량은 0보다 커야 합니다.");
+ }
+ if (this.quantity + quantity > MAX_QUANTITY) {
+ throw new IllegalStateException("최대 허용 수량을 초과할 수 없습니다.");
+ }
this.quantity += quantity;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public void addQuantity(int quantity) { | |
| this.quantity += quantity; | |
| } | |
| public void addQuantity(int quantity) { | |
| if (quantity <= 0) { | |
| throw new IllegalArgumentException("추가할 수량은 0보다 커야 합니다."); | |
| } | |
| if (this.quantity + quantity > MAX_QUANTITY) { | |
| throw new IllegalStateException("최대 허용 수량을 초과할 수 없습니다."); | |
| } | |
| this.quantity += quantity; | |
| } |
| public LineItem(String id, String productId, int quantity) { | ||
| this.id = id; | ||
| this.productId = productId; | ||
| this.quantity = quantity; | ||
| } | ||
|
|
||
| public LineItem(String productId, int quantity) { | ||
| this.productId = productId; | ||
| this.quantity = quantity; | ||
| } |
There was a problem hiding this comment.
생성자 입력값 검증 필요
생성자에서 입력값 검증이 누락되어 있습니다. 잘못된 입력으로 인한 문제를 방지하기 위해 다음과 같은 검증을 추가해 주세요:
public LineItem(String id, String productId, int quantity) {
+ if (id == null || id.isEmpty()) {
+ throw new IllegalArgumentException("ID는 null이거나 비어있을 수 없습니다.");
+ }
+ if (productId == null || productId.isEmpty()) {
+ throw new IllegalArgumentException("상품 ID는 null이거나 비어있을 수 없습니다.");
+ }
+ if (quantity <= 0) {
+ throw new IllegalArgumentException("수량은 0보다 커야 합니다.");
+ }
this.id = id;
this.productId = productId;
this.quantity = quantity;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public LineItem(String id, String productId, int quantity) { | |
| this.id = id; | |
| this.productId = productId; | |
| this.quantity = quantity; | |
| } | |
| public LineItem(String productId, int quantity) { | |
| this.productId = productId; | |
| this.quantity = quantity; | |
| } | |
| public LineItem(String id, String productId, int quantity) { | |
| if (id == null || id.isEmpty()) { | |
| throw new IllegalArgumentException("ID는 null이거나 비어있을 수 없습니다."); | |
| } | |
| if (productId == null || productId.isEmpty()) { | |
| throw new IllegalArgumentException("상품 ID는 null이거나 비어있을 수 없습니다."); | |
| } | |
| if (quantity <= 0) { | |
| throw new IllegalArgumentException("수량은 0보다 커야 합니다."); | |
| } | |
| this.id = id; | |
| this.productId = productId; | |
| this.quantity = quantity; | |
| } | |
| public LineItem(String productId, int quantity) { | |
| this.productId = productId; | |
| this.quantity = quantity; | |
| } |
| public Cart getCart() { | ||
|
|
||
| Cart cart = cartRepository.find(); | ||
|
|
||
| List<String> productIds = cart.getLineItems().stream() | ||
| .map(LineItem::getProductId) | ||
| .toList(); | ||
|
|
||
| Map<String, Product> products = new HashMap<>(); | ||
| productRepository.findAllByIds(productIds).forEach( | ||
| product -> products.put(product.getId(), product) | ||
| ); | ||
|
|
||
| cart.getLineItems().forEach(lineItem -> { | ||
| Product product = products.get(lineItem.getProductId()); | ||
| lineItem.setProduct(product); | ||
| }); | ||
|
|
||
| return cart; | ||
| } |
There was a problem hiding this comment.
getCart 메서드에 안전성 개선이 필요합니다.
products Map에서 product를 조회할 때 null 체크가 없어 NullPointerException이 발생할 수 있습니다.
다음과 같이 수정을 제안합니다:
cart.getLineItems().forEach(lineItem -> {
Product product = products.get(lineItem.getProductId());
+ if (product == null) {
+ throw new ProductNotFoundException("Product not found with ID: " + lineItem.getProductId());
+ }
lineItem.setProduct(product);
});📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public Cart getCart() { | |
| Cart cart = cartRepository.find(); | |
| List<String> productIds = cart.getLineItems().stream() | |
| .map(LineItem::getProductId) | |
| .toList(); | |
| Map<String, Product> products = new HashMap<>(); | |
| productRepository.findAllByIds(productIds).forEach( | |
| product -> products.put(product.getId(), product) | |
| ); | |
| cart.getLineItems().forEach(lineItem -> { | |
| Product product = products.get(lineItem.getProductId()); | |
| lineItem.setProduct(product); | |
| }); | |
| return cart; | |
| } | |
| public Cart getCart() { | |
| Cart cart = cartRepository.find(); | |
| List<String> productIds = cart.getLineItems().stream() | |
| .map(LineItem::getProductId) | |
| .toList(); | |
| Map<String, Product> products = new HashMap<>(); | |
| productRepository.findAllByIds(productIds).forEach( | |
| product -> products.put(product.getId(), product) | |
| ); | |
| cart.getLineItems().forEach(lineItem -> { | |
| Product product = products.get(lineItem.getProductId()); | |
| if (product == null) { | |
| throw new ProductNotFoundException("Product not found with ID: " + lineItem.getProductId()); | |
| } | |
| lineItem.setProduct(product); | |
| }); | |
| return cart; | |
| } |
| public void add(LineItem lineItem) { | ||
| Document document = new Document() | ||
| .append("product_id", lineItem.getProductId()) | ||
| .append("quantity", lineItem.getQuantity()); | ||
|
|
||
| collection.insertOne(document); | ||
| } |
There was a problem hiding this comment.
예외 처리가 필요합니다.
MongoDB 작업 시 발생할 수 있는 예외에 대한 처리가 없습니다.
다음과 같이 예외 처리를 추가하는 것을 제안합니다:
public void add(LineItem lineItem) {
+ try {
Document document = new Document()
.append("product_id", lineItem.getProductId())
.append("quantity", lineItem.getQuantity());
collection.insertOne(document);
+ } catch (MongoException e) {
+ throw new RepositoryException("라인 아이템 추가 중 오류 발생", e);
+ }
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| public void add(LineItem lineItem) { | |
| Document document = new Document() | |
| .append("product_id", lineItem.getProductId()) | |
| .append("quantity", lineItem.getQuantity()); | |
| collection.insertOne(document); | |
| } | |
| public void add(LineItem lineItem) { | |
| try { | |
| Document document = new Document() | |
| .append("product_id", lineItem.getProductId()) | |
| .append("quantity", lineItem.getQuantity()); | |
| collection.insertOne(document); | |
| } catch (MongoException e) { | |
| throw new RepositoryException("라인 아이템 추가 중 오류 발생", e); | |
| } | |
| } |
Summary by CodeRabbit