Skip to content
This repository has been archived by the owner on Aug 13, 2022. It is now read-only.

[#26] 장바구니 도메인 추가 #44

Open
wants to merge 6 commits into
base: feature/39
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 38 additions & 11 deletions src/main/java/me/jjeda/mall/cart/service/CartService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,65 @@
import me.jjeda.mall.cart.domain.Cart;
import me.jjeda.mall.cart.domain.CartItem;
import me.jjeda.mall.cart.repository.CartRedisRepository;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class CartService {
private final CartRedisRepository cartRedisRepository;
private final RedisTemplate redisTemplate;

public Cart getCart(String id) {
return cartRedisRepository.findById(id).orElseThrow(EntityNotFoundException::new);
}

@Transactional
public Cart addItem(String id, CartItem cartItem) {
final Cart cart;

if (!cartRedisRepository.existsById(id)) {
cart = Cart.of(id);
final String key = String.format("cart:%s", id);
// "_class", "id" 필드를 제외하고 "cartItemList[n]" 의 필드개수 6개로 나누어주면 상품개수
int cartItemSize = (int)((redisTemplate.opsForHash().size(key) - 2) / 6);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2, 6 같은 수는 상수로 만들면 더 소스를 이해하기 좋을 것 같습니다

boolean hasKey = redisTemplate.hasKey(key);
final Map<String, Object> map;

if (hasKey) {
map = convertCartItemToMap(cartItemSize,cartItem);
} else {
cart = getCart(id);
map = convertCartItemToMap(0,cartItem);
}

List<CartItem> cartItemList = cart.getCartItemList();
cartItemList.add(cartItem);
return cartRedisRepository.save(cart);
redisTemplate.execute(new SessionCallback() {
@Override
public Object execute(RedisOperations redisOperations) throws DataAccessException {
redisOperations.watch(key);
redisOperations.multi();
redisOperations.opsForHash().putAll(key,map);
return redisOperations.exec();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

만약 중간에 예외가 발생하면 어떻게 될까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오호 WATCH 는 버전정보만 비교하는건가보네요~
자동으로 DISCARD 될 줄알았는데 다시 읽어보니 아닌 것같군요

}
});

return getCart(id);
}

private Map<String, Object> convertCartItemToMap(int size, CartItem cartItem) {
Map<String, Object> map = new HashMap<>();
map.put(String.format("cartItemList.[%d].item.id", size), cartItem.getItem().getId());
map.put(String.format("cartItemList.[%d].item.name", size), cartItem.getItem().getName());
map.put(String.format("cartItemList.[%d].item.price", size), cartItem.getItem().getPrice());
map.put(String.format("cartItemList.[%d].item.stockQuantity", size), cartItem.getItem().getStockQuantity());
map.put(String.format("cartItemList.[%d].price", size), cartItem.getPrice());
map.put(String.format("cartItemList.[%d].quantity", size), cartItem.getQuantity());
return map;
}

@Transactional
public Cart removeItem(String id, CartItem cartItem) {
Cart cart = getCart(id);
List<CartItem> cartItemList = cart.getCartItemList();
Expand All @@ -43,7 +71,6 @@ public Cart removeItem(String id, CartItem cartItem) {
return cartRedisRepository.save(cart);
}

@Transactional
public void deleteCart(String id) {
cartRedisRepository.delete(getCart(id));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public void add_item() throws Exception {
cartRedisRepository.save(cart);

//when & then
mockMvc.perform(put("/api/carts/add")
mockMvc.perform(put("/api/carts/items/new")
.header(HttpHeaders.AUTHORIZATION, getAccessToken())
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(cartItem2)))
Expand Down