Skip to content

Commit

Permalink
Merge pull request #31 from 2024-9oormthonUNIV-Team-7/feat/#28
Browse files Browse the repository at this point in the history
[feat] 즐겨찾기 추가
  • Loading branch information
codingssagae authored Sep 28, 2024
2 parents 974a519 + bd9d2e6 commit 3641354
Show file tree
Hide file tree
Showing 13 changed files with 361 additions and 5 deletions.
12 changes: 12 additions & 0 deletions src/main/java/exception/FavoriteNotFoundException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class FavoriteNotFoundException extends RuntimeException {

public FavoriteNotFoundException(String message){
super(message);
}
}
11 changes: 11 additions & 0 deletions src/main/java/exception/UserNotFoundException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message){
super(message);
}
}
74 changes: 74 additions & 0 deletions src/main/java/goormthonUniv/floating/DataInitializer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package goormthonUniv.floating;

import goormthonUniv.floating.domain.*;
import goormthonUniv.floating.repository.FavoriteRepository;
import goormthonUniv.floating.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class DataInitializer implements CommandLineRunner {

private final UserRepository userRepository;
private final FavoriteRepository favoriteRepository;

// 생성자 주입을 사용하여 리포지토리 주입
public DataInitializer(UserRepository userRepository, FavoriteRepository favoriteRepository) {
this.userRepository = userRepository;
this.favoriteRepository = favoriteRepository;
}

@Override
public void run(String... args) throws Exception {
// User 더미 데이터 생성
User user1 = new User();
user1.setGoogleId("googleId_1");
user1.setEmail("[email protected]");
user1.setRole(Role.GUEST); // Role 설정
user1.setName("John Doe");

User user2 = new User();
user2.setGoogleId("googleId_2");
user2.setEmail("[email protected]");
user2.setRole(Role.GUEST); // Role 설정
user2.setName("Jane Smith");

// 사용자 저장
userRepository.saveAll(List.of(user1, user2));

// Favorite 더미 데이터 생성
Favorite favorite1 = new Favorite();
favorite1.setUser(user1);
favorite1.setCategory(FavoriteCategory.balance_game);
favorite1.setItemId(1L);
favorite1.setCreateTime(LocalDateTime.now());

Favorite favorite2 = new Favorite();
favorite2.setUser(user1);
favorite2.setCategory(FavoriteCategory.mini_game);
favorite2.setItemId(2L);
favorite2.setCreateTime(LocalDateTime.now());

Favorite favorite3 = new Favorite();
favorite3.setUser(user1);
favorite3.setCategory(FavoriteCategory.mini_game);
favorite3.setItemId(3L);
favorite3.setCreateTime(LocalDateTime.now());

Favorite favorite4 = new Favorite();
favorite4.setUser(user1);
favorite4.setCategory(FavoriteCategory.small_talk);
favorite4.setItemId(5L);
favorite4.setCreateTime(LocalDateTime.now());

// 즐겨찾기 데이터 저장
favoriteRepository.saveAll(List.of(favorite1, favorite2,favorite3,favorite4));

System.out.println("더미 데이터 삽입 완료");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package goormthonUniv.floating.controller;

import goormthonUniv.floating.domain.Favorite;
import goormthonUniv.floating.domain.User;
import goormthonUniv.floating.repository.FavoriteRepository;
import goormthonUniv.floating.repository.UserRepository;
import goormthonUniv.floating.response.FavoriteResponse;
import goormthonUniv.floating.service.FavoriteService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import request.FavoriteRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/v1")
@RequiredArgsConstructor
@Slf4j
public class FavoriteController {

private final FavoriteService favoriteService;
@GetMapping("/favorites/{googleId}")
public ResponseEntity<Map<String, Object>> getFavoritesByGoogleId(@PathVariable String googleId) {
List<FavoriteResponse> favoriteResponses = favoriteService.getFavoritesByGoogleId(googleId);

Map<String, Object> response = new HashMap<>();
response.put("favorite", favoriteResponses);
response.put("status", 200);
response.put("message", "즐겨찾기 조회 성공");
return ResponseEntity.ok(response);
}


@PostMapping("/post-favorite")
public ResponseEntity<Map<String, Object>> postFavorite(@RequestBody Map<String, Object> requestBody) {
String email = (String) requestBody.get("email");
String category = (String) requestBody.get("category");
Long itemId = Long.valueOf(requestBody.get("itemId").toString()); // Long 변환 처리

favoriteService.addFavorite(email, category, itemId);

Map<String, Object> response = new HashMap<>();
response.put("status", 200);
response.put("message", "즐겨찾기 추가 성공");
return ResponseEntity.ok(response);
}
@DeleteMapping("/delete-favorite")
public ResponseEntity<Map<String,Object>> deleteFavorite( @RequestParam("google_Id") String googleId,
@RequestParam("favorite_Id") Long favoriteId){
favoriteService.deleteFavoriteByGoogleIdAndItemId(googleId,favoriteId);
Map<String, Object> response = new HashMap<>();
response.put("status",200);
response.put("message", "즐겨찾기 항목 삭제 성공");
return ResponseEntity.ok(response);
}


}
6 changes: 2 additions & 4 deletions src/main/java/goormthonUniv/floating/domain/TalkSubject.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package goormthonUniv.floating.domain;


import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

Expand All @@ -20,6 +17,7 @@ public class TalkSubject {
private String subject;
private String description;

@Enumerated(EnumType.STRING)
private Category category;

}
2 changes: 1 addition & 1 deletion src/main/java/goormthonUniv/floating/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,4 @@ public String getRoleKey() {
}


}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package goormthonUniv.floating.repository;

import goormthonUniv.floating.domain.Favorite;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface FavoriteRepository extends JpaRepository<Favorite, Long> {
List<Favorite> findByUserId(Long userId);
Optional<Favorite> findByUserIdAndItemId(Long userId, Long itemid);

List<Favorite> findByUserIdOrderByCreateTimeDesc(Long userId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@

import goormthonUniv.floating.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByGoogleId(String googleId);

Optional<User> findByEmail(String email);
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package goormthonUniv.floating.response;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class FavoriteResponse {

private Long id;
private String category;
private Long itemId;

// mini_game의 경우
private String name;
private String description;

// talk_subject의 경우
private String subject;
private String talkDescription;

// balance_game의 경우
private String questionA;
private String questionB;

public FavoriteResponse(Long id, String category, Long itemId) {
this.id = id;
this.category = category;
this.itemId = itemId;
}
}
103 changes: 103 additions & 0 deletions src/main/java/goormthonUniv/floating/service/FavoriteService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package goormthonUniv.floating.service;

import exception.FavoriteNotFoundException;
import exception.UserNotFoundException;
import goormthonUniv.floating.domain.*;
import goormthonUniv.floating.repository.*;
import goormthonUniv.floating.response.FavoriteResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class FavoriteService {

private final FavoriteRepository favoriteRepository;
private final UserRepository userRepository;


@Transactional
public void addFavorite(String email, String category, Long itemId){
Optional<User> user = userRepository.findByEmail(email);
Favorite favorite = new Favorite();
favorite.setUser(user.get());
favorite.setCategory(FavoriteCategory.valueOf(category));
System.out.println("itemId = " + itemId);
favorite.setItemId(itemId);
favorite.setCreateTime(LocalDateTime.now());

favoriteRepository.save(favorite);
}

private final MiniGameRepository miniGameRepository; // 미니게임 리포지토리
private final TalkSubjectRepository talkSubjectRepository; // 토크 주제 리포지토리
private final BalanceGameRepository balanceGameRepository; // 밸런스 게임 리포지토리

public List<FavoriteResponse> getFavoritesByGoogleId(String googleId) {
Optional<User> user = userRepository.findByGoogleId(googleId);
if (user.isEmpty()) {
throw new UserNotFoundException("User not found for googleId: " + googleId);
}

// createTime 기준으로 최신순 정렬하여 가져오기
List<Favorite> favorites = favoriteRepository.findByUserIdOrderByCreateTimeDesc(user.get().getId());

return favorites.stream().map(favorite -> {
FavoriteResponse response = new FavoriteResponse(
favorite.getId(),
favorite.getCategory().toString(),
favorite.getItemId()
);

switch (favorite.getCategory()) {
case mini_game -> {
MiniGame miniGame = miniGameRepository.findById(favorite.getItemId())
.orElseThrow(() -> new RuntimeException("미니게임 데이터를 찾을 수 없습니다."));
response.setName(miniGame.getName());
response.setDescription(miniGame.getDescription());
}
case small_talk -> {
TalkSubject talkSubject = talkSubjectRepository.findById(favorite.getItemId())
.orElseThrow(() -> new RuntimeException("토크 주제 데이터를 찾을 수 없습니다."));
response.setSubject(talkSubject.getSubject());
response.setTalkDescription(talkSubject.getDescription());
}
case balance_game -> {
BalanceGame balanceGame = balanceGameRepository.findById(favorite.getItemId())
.orElseThrow(() -> new RuntimeException("밸런스 게임 데이터를 찾을 수 없습니다."));
response.setQuestionA(balanceGame.getQuestionA());
response.setQuestionB(balanceGame.getQuestionB());
}
default -> throw new IllegalArgumentException("잘못된 카테고리: " + favorite.getCategory());
}

return response;
}).collect(Collectors.toList());
}


@Transactional
public void deleteFavoriteByGoogleIdAndItemId(String googleId, Long favoriteId){
Optional<User> user = userRepository.findByGoogleId(googleId);
if (user.isPresent()) {
// userId와 itemId로 즐겨찾기 항목을 조회
Optional<Favorite> favorite = favoriteRepository.findById(favoriteId);

if (favorite.isPresent()) {
// 즐겨찾기 항목 삭제
favoriteRepository.delete(favorite.get());
} else {
throw new FavoriteNotFoundException("해당 즐겨찾기 항목이 존재하지 않습니다.");
}
} else {
throw new UserNotFoundException("해당 google_id로 유저를 찾을 수 없습니다.");
}
}

}
14 changes: 14 additions & 0 deletions src/main/java/goormthonUniv/floating/service/UserService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package goormthonUniv.floating.service;

import goormthonUniv.floating.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class UserService {

private final UserRepository userRepository;

}
14 changes: 14 additions & 0 deletions src/main/java/request/FavoriteRequest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package request;

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class FavoriteRequest {

private String email;
private String category;
private Long itemId;

}
Loading

0 comments on commit 3641354

Please sign in to comment.