Skip to content

Commit

Permalink
[FIX] FE에서 Item을 식별하는 코드가 제대로 설정되지 않는 버그 픽스 (#189)
Browse files Browse the repository at this point in the history
* refactor: Item 식별 전용 Column 생성

- Item 식별 시 사용할 전용 Column 생성
- 식별 전용으로 사용할 것이기 때문에 unique=true로 설정

* feat: data.sql의 insert문을 변경된 구조에 맞게 수정

* feat: 식별자를 통해 Item을 반환하는 코드 및 테스트 코드 추가

- ItemProvider, ItemService에 식별자(identifier)를 통해 Item 객체를 찾는 코드 추가
- ItemController에서 전달받은 값(식별자)를 통해 Item 객체를 받은 후 전달하는 코드 추가
- 관련 테스트 코드 추가
  • Loading branch information
SSung023 authored May 30, 2024
1 parent 66a6f76 commit b6c895f
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
import com.genius.gitget.global.util.response.dto.CommonResponse;
import com.genius.gitget.global.util.response.dto.ListResponse;
import com.genius.gitget.global.util.response.dto.SingleResponse;
import com.genius.gitget.store.item.domain.Item;
import com.genius.gitget.store.item.domain.ItemCategory;
import com.genius.gitget.store.item.dto.ItemResponse;
import com.genius.gitget.store.item.dto.ItemUseResponse;
import com.genius.gitget.store.item.dto.ProfileResponse;
import com.genius.gitget.store.item.service.ItemProvider;
import com.genius.gitget.store.item.service.ItemService;
import java.time.LocalDate;
import java.util.List;
Expand All @@ -28,6 +30,7 @@
@RequestMapping("/api")
public class ItemController {
private final ItemService itemService;
private final ItemProvider itemProvider;

@GetMapping("/items")
public ResponseEntity<ListResponse<ItemResponse>> getItemList(
Expand All @@ -47,26 +50,28 @@ public ResponseEntity<ListResponse<ItemResponse>> getItemList(
);
}

@PostMapping("/items/order/{itemId}")
@PostMapping("/items/order/{identifier}")
public ResponseEntity<SingleResponse<ItemResponse>> purchaseItem(
@AuthenticationPrincipal UserPrincipal userPrincipal,
@PathVariable Long itemId
@PathVariable int identifier
) {
ItemResponse itemResponse = itemService.orderItem(userPrincipal.getUser(), itemId);
Item item = itemProvider.findByIdentifier(identifier);
ItemResponse itemResponse = itemService.orderItem(userPrincipal.getUser(), item.getId());

return ResponseEntity.ok().body(
new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), itemResponse)
);
}

@PostMapping("/items/use/{itemId}")
@PostMapping("/items/use/{identifier}")
public ResponseEntity<CommonResponse> useItem(
@AuthenticationPrincipal UserPrincipal userPrincipal,
@PathVariable Long itemId,
@PathVariable int identifier,
@RequestParam(required = false) Long instanceId
) {
ItemUseResponse itemUseResponse = itemService.useItem(userPrincipal.getUser(), itemId, instanceId,
LocalDate.now());
Item item = itemProvider.findByIdentifier(identifier);
ItemUseResponse itemUseResponse = itemService.useItem(userPrincipal.getUser(), item.getId(),
instanceId, LocalDate.now());

return ResponseEntity.ok().body(
new SingleResponse<>(SUCCESS.getStatus(), SUCCESS.getMessage(), itemUseResponse)
Expand Down
7 changes: 6 additions & 1 deletion src/main/java/com/genius/gitget/store/item/domain/Item.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ public class Item extends BaseTimeEntity {
@OneToMany(mappedBy = "item")
private List<Orders> ordersList = new ArrayList<>();

@Column(unique = true)
private int identifier;

private String name;

private int cost;
Expand All @@ -38,9 +41,11 @@ public class Item extends BaseTimeEntity {
private String details;

@Builder
public Item(String name, int cost, ItemCategory itemCategory, String details) {
public Item(String name, int cost, int identifier,
ItemCategory itemCategory, String details) {
this.name = name;
this.cost = cost;
this.identifier = identifier;
this.itemCategory = itemCategory;
this.details = details;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@

@Data
public class ItemResponse {
private Long itemId;
private int itemId;
private ItemCategory itemCategory;
private String name;
private String details;
private int cost;
private int count;

protected ItemResponse(Item item, int count) {
this.itemId = item.getId();
this.itemId = item.getIdentifier();
this.itemCategory = item.getItemCategory();
this.name = item.getName();
this.details = item.getDetails();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.genius.gitget.store.item.domain.Item;
import com.genius.gitget.store.item.domain.ItemCategory;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
Expand All @@ -11,4 +12,6 @@ public interface ItemRepository extends JpaRepository<Item, Long> {

@Query("select i from Item i where i.itemCategory = :category")
List<Item> findAllByCategory(@Param("category") ItemCategory itemCategory);

Optional<Item> findByIdentifier(@Param("identifier") int identifier);
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.genius.gitget.store.item.service;

import com.genius.gitget.global.util.exception.BusinessException;
import com.genius.gitget.global.util.exception.ErrorCode;
import com.genius.gitget.store.item.domain.Item;
import com.genius.gitget.store.item.domain.ItemCategory;
import com.genius.gitget.store.item.repository.ItemRepository;
import com.genius.gitget.global.util.exception.BusinessException;
import com.genius.gitget.global.util.exception.ErrorCode;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
Expand All @@ -21,6 +21,11 @@ public Item findById(Long itemId) {
.orElseThrow(() -> new BusinessException(ErrorCode.ITEM_NOT_FOUND));
}

public Item findByIdentifier(int identifier) {
return itemRepository.findByIdentifier(identifier)
.orElseThrow(() -> new BusinessException(ErrorCode.ITEM_NOT_FOUND));
}

public List<Item> findAllByCategory(ItemCategory itemCategory) {
return itemRepository.findAllByCategory(itemCategory);
}
Expand Down
26 changes: 15 additions & 11 deletions src/main/resources/data.sql
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
INSERT INTO item (cost, created_at, deleted_at, updated_at, details, name, item_category)
INSERT INTO item (identifier, cost, details, name, item_category)
SELECT *
FROM (SELECT 100 AS cost,
NULL AS created_at,
NULL AS deleted_at,
NULL AS updated_at,
FROM (SELECT 1 AS identifier,
100 AS cost,
'프로필을 꾸밀 수 있는 프레임입니다.' AS details,
'성탄절 프레임' AS name,
'PROFILE_FRAME' AS item_category
UNION ALL
SELECT 100, NULL, NULL, NULL, '프로필을 꾸밀 수 있는 프레임입니다.', '어둠의 힘 프레임', 'PROFILE_FRAME'
SELECT 2,
100,
'프로필을 꾸밀 수 있는 프레임입니다.',
'어둠의 힘 프레임',
'PROFILE_FRAME'
UNION ALL
SELECT 100, NULL, NULL, NULL, '오늘의 인증을 넘길 수 있는 아이템입니다.', '인증 패스권', 'CERTIFICATION_PASSER'
SELECT 3,
100,
'오늘의 인증을 넘길 수 있는 아이템입니다.',
'인증 패스권',
'CERTIFICATION_PASSER'
UNION ALL
SELECT 100,
NULL,
NULL,
NULL,
SELECT 4,
100,
'아이템 사용 시, 챌린지 성공 보상을 2배로 획득할 수 있는 아이템입니다.',
'챌린지 보상 획득 2배 아이템',
'POINT_MULTIPLIER') AS new_items
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package com.genius.gitget.challenge.item.service;

import static com.genius.gitget.store.item.domain.ItemCategory.CERTIFICATION_PASSER;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.genius.gitget.global.util.exception.BusinessException;
import com.genius.gitget.global.util.exception.ErrorCode;
import com.genius.gitget.store.item.domain.Item;
import com.genius.gitget.store.item.domain.ItemCategory;
import com.genius.gitget.store.item.repository.ItemRepository;
import com.genius.gitget.global.util.exception.BusinessException;
import com.genius.gitget.global.util.exception.ErrorCode;
import com.genius.gitget.store.item.service.ItemProvider;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -34,7 +35,7 @@ class ItemProviderTest {
@EnumSource(mode = Mode.INCLUDE, names = {"POINT_MULTIPLIER", "CERTIFICATION_PASSER"})
public void should_findItems_when_passCategory(ItemCategory itemCategory) {
//given
Item item = getSavedItem(itemCategory);
Item item = getSavedItem(10, itemCategory);

//when
List<Item> items = itemProvider.findAllByCategory(itemCategory);
Expand All @@ -49,7 +50,7 @@ public void should_findItems_when_passCategory(ItemCategory itemCategory) {
@DisplayName("DB에 저장되어 있는 아이템을 식별자 PK를 통해 조회할 수 있다.")
public void should_findItem_when_passPK() {
//given
Item item = getSavedItem(ItemCategory.CERTIFICATION_PASSER);
Item item = getSavedItem(10, CERTIFICATION_PASSER);

//when
Item foundItem = itemProvider.findById(item.getId());
Expand All @@ -68,9 +69,25 @@ public void should_throwException_when_pkNotExist() {
.hasMessageContaining(ErrorCode.ITEM_NOT_FOUND.getMessage());
}

private Item getSavedItem(ItemCategory itemCategory) {
@Test
@DisplayName("식별 전용 값인 identifier를 통해 아이템을 조회할 수 있다.")
public void should_findItem_by_identifier() {
//given
int identifier = 10;
Item item = getSavedItem(identifier, CERTIFICATION_PASSER);

//when
Item byIdentifier = itemProvider.findByIdentifier(identifier);

//then
assertThat(item.getId()).isEqualTo(byIdentifier.getId());
assertThat(byIdentifier.getItemCategory()).isEqualTo(CERTIFICATION_PASSER);
}

private Item getSavedItem(int identifier, ItemCategory itemCategory) {
return itemRepository.save(
Item.builder()
.identifier(identifier)
.cost(100)
.itemCategory(itemCategory)
.build()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public void should_purchaseItem_when_passPK(ItemCategory itemCategory) {
ItemResponse itemResponse = itemService.orderItem(user, item.getId());

//then
assertThat(itemResponse.getItemId()).isEqualTo(item.getId());
assertThat(itemResponse.getItemId()).isEqualTo(item.getIdentifier());
assertThat(itemResponse.getName()).isEqualTo(item.getName());
assertThat(itemResponse.getCost()).isEqualTo(item.getCost());
assertThat(itemResponse.getCount()).isEqualTo(1);
Expand Down Expand Up @@ -416,7 +416,7 @@ public void should_unmountFrame_when_mountAlready() {
ProfileResponse profileResponse = itemService.unmountFrame(user).get(0);

//then
assertThat(profileResponse.getItemId()).isEqualTo(item.getId());
assertThat(profileResponse.getItemId()).isEqualTo(item.getIdentifier());
assertThat(profileResponse.getCost()).isEqualTo(item.getCost());
assertThat(profileResponse.getItemCategory()).isEqualTo(ItemCategory.PROFILE_FRAME);
assertThat(profileResponse.getEquipStatus()).isEqualTo(EquipStatus.AVAILABLE.getTag());
Expand Down Expand Up @@ -466,6 +466,7 @@ private User getSavedUser() {

private Item getSavedItem(ItemCategory itemCategory) {
return itemRepository.save(Item.builder()
.identifier(10)
.itemCategory(itemCategory)
.cost(100)
.name(itemCategory.getName())
Expand Down

0 comments on commit b6c895f

Please sign in to comment.