diff --git a/src/main/java/treehouse/server/api/user/persistence/FcmTokenRepository.java b/src/main/java/treehouse/server/api/user/persistence/FcmTokenRepository.java index 7cd2c87..8dc210e 100644 --- a/src/main/java/treehouse/server/api/user/persistence/FcmTokenRepository.java +++ b/src/main/java/treehouse/server/api/user/persistence/FcmTokenRepository.java @@ -14,7 +14,11 @@ public interface FcmTokenRepository extends JpaRepository { void deleteAllByUser(User user); + void deleteByUser(User user); + + boolean existsByUser(User user); + boolean existsByUserAndToken(User user, String token); - List findAllByUser(User user); +// List findAllByUser(User user); } diff --git a/src/main/java/treehouse/server/global/entity/User/FcmToken.java b/src/main/java/treehouse/server/global/entity/User/FcmToken.java index 3fecbf1..4f339e2 100644 --- a/src/main/java/treehouse/server/global/entity/User/FcmToken.java +++ b/src/main/java/treehouse/server/global/entity/User/FcmToken.java @@ -19,7 +19,7 @@ public class FcmToken extends BaseDateTimeEntity { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @ManyToOne(fetch = FetchType.LAZY) + @OneToOne private User user; private String token; diff --git a/src/main/java/treehouse/server/global/exception/GlobalErrorCode.java b/src/main/java/treehouse/server/global/exception/GlobalErrorCode.java index 57f457b..e81761e 100644 --- a/src/main/java/treehouse/server/global/exception/GlobalErrorCode.java +++ b/src/main/java/treehouse/server/global/exception/GlobalErrorCode.java @@ -106,6 +106,7 @@ public enum GlobalErrorCode implements BaseErrorCode{ PHONE_AUTH_TIMEOUT(BAD_REQUEST, "NCP400_3", "인증 시간이 초과되었습니다."), FCM_ALREADY_EXISTS_TOKEN(BAD_REQUEST, "FCM400_1", "이미 저장되어 있는 FCM 토큰입니다."), + FCM_TOKEN_NOT_EXISTS(BAD_REQUEST,"FCM400_2", "해당 유저의 FCM Token 이 존재하지 않습니다."), FCM_ACCESS_TOKEN_REQUEST_ERROR(INTERNAL_SERVER_ERROR, "FCM500_2", "서버 에러, FCM 서버에 AccessToken 요청할 때 에러 발생."), FCM_SEND_MESSAGE_ERROR(INTERNAL_SERVER_ERROR , "FCM500_3", "서버 에러, FCM 서버에 메시지를 전송할 때 에러 발생. FcmToken이 유효한지 확인해주세요."), ; diff --git a/src/main/java/treehouse/server/global/fcm/service/FcmService.java b/src/main/java/treehouse/server/global/fcm/service/FcmService.java index 4b33396..9595369 100644 --- a/src/main/java/treehouse/server/global/fcm/service/FcmService.java +++ b/src/main/java/treehouse/server/global/fcm/service/FcmService.java @@ -4,6 +4,7 @@ import com.google.firebase.messaging.FirebaseMessagingException; import com.google.firebase.messaging.Message; import com.google.firebase.messaging.Notification; +import lombok.AllArgsConstructor; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,10 +20,11 @@ import treehouse.server.global.fcm.dto.FCMDto; import java.util.List; +import java.util.Optional; @Service @RequiredArgsConstructor -@Transactional(readOnly = true) +//@Transactional(readOnly = true) public class FcmService { Logger logger = LoggerFactory.getLogger(FcmService.class); @@ -49,17 +51,20 @@ public void testFCMService(String fcmToken) @Transactional(readOnly = false) public UserResponseDTO.saveFcmToken saveFcmToken(User user, FCMDto.saveFcmTokenDto request) { - boolean isSuccess = false; - logger.error("토큰 값 : {}",request.getFcmToken()); - if (fcmTokenRepository.existsByUserAndToken(user, request.getFcmToken())) { - throw new FcmException(GlobalErrorCode.FCM_ALREADY_EXISTS_TOKEN); - }else{ + boolean isSuccess = true; + logger.info("토큰 값 : {}", request.getFcmToken()); + + + // 한 user 당 가장 최신의 fcm token 값 하나만 db 에 저장하도록 수정 + if (fcmTokenRepository.existsByUser(user)) { + FcmToken fcmToken = fcmTokenRepository.findByUser(user).orElseThrow(() -> new FcmException(GlobalErrorCode.FCM_TOKEN_NOT_EXISTS)); + fcmToken.update(request.getFcmToken()); + } else { fcmTokenRepository.save(FcmToken.builder() .user(user) .token(request.getFcmToken()) .build() ); - isSuccess = true; } return UserMapper.toSaveFcmToken(user, isSuccess); } @@ -67,30 +72,27 @@ public UserResponseDTO.saveFcmToken saveFcmToken(User user, FCMDto.saveFcmTokenD public void sendFcmMessage(User receiver, String title, String body) { - List fcmTokenList = fcmTokenRepository.findAllByUser(receiver); - if (fcmTokenList.isEmpty()) { - return; - } + FcmToken fcmToken = fcmTokenRepository.findByUser(receiver).orElseThrow(() -> new FcmException(GlobalErrorCode.FCM_TOKEN_NOT_EXISTS)); - for (FcmToken fcmToken : fcmTokenList) { - String token = fcmToken.getToken(); - logger.info("전송하고자 하는 FCM 토큰 값 : " + token); - Message message = Message.builder() - .setToken(token) - .setNotification( - Notification.builder() - .setTitle(title) - .setBody(body) - .build()) - .build(); - try { - String response = FirebaseMessaging.getInstance().send(message); - logger.info("the response of request FCM : {}",response); - } catch (FirebaseMessagingException e) { - throw new FcmException(GlobalErrorCode.FCM_SEND_MESSAGE_ERROR); - } - } + String token = fcmToken.getToken(); + logger.info("전송하고자 하는 FCM 토큰 값 : " + token); + + Message message = Message.builder() + .setToken(token) + .setNotification( + Notification.builder() + .setTitle(title) + .setBody(body) + .build()) + .build(); + try { + String response = FirebaseMessaging.getInstance().send(message); + logger.info("the response of request FCM : {}",response); + } catch (FirebaseMessagingException e) { + logger.error("FCM 푸시 알림 전송 실패, 이유 : {}", e.getMessage()); + throw new FcmException(GlobalErrorCode.FCM_SEND_MESSAGE_ERROR); + } } @@ -98,4 +100,5 @@ public void sendFcmMessage(User receiver, String title, String body) { public void deleteAllFcmToken(User user) { fcmTokenRepository.deleteAllByUser(user); } + }