|
| 1 | +package com.semosan.api.domain.notification.service; |
| 2 | + |
| 3 | +import com.semosan.api.common.exception.GeneralException; |
| 4 | +import com.semosan.api.common.status.ErrorStatus; |
| 5 | +import com.semosan.api.domain.notification.dispatcher.NotificationDispatchCommand; |
| 6 | +import com.semosan.api.domain.notification.dispatcher.NotificationDispatcher; |
| 7 | +import com.semosan.api.domain.notification.entity.FcmToken; |
| 8 | +import com.semosan.api.domain.notification.entity.Notification; |
| 9 | +import com.semosan.api.domain.notification.enums.NotificationType; |
| 10 | +import com.semosan.api.domain.notification.repository.FcmTokenRepository; |
| 11 | +import com.semosan.api.domain.notification.repository.NotificationRepository; |
| 12 | +import com.semosan.api.domain.user.repository.UserRepository; |
| 13 | +import lombok.RequiredArgsConstructor; |
| 14 | +import lombok.extern.slf4j.Slf4j; |
| 15 | +import org.springframework.stereotype.Service; |
| 16 | +import org.springframework.transaction.annotation.Transactional; |
| 17 | + |
| 18 | +import java.util.List; |
| 19 | +import java.util.Map; |
| 20 | + |
| 21 | +@Slf4j |
| 22 | +@Service |
| 23 | +@RequiredArgsConstructor |
| 24 | +public class NotificationService { |
| 25 | + |
| 26 | + private final NotificationDispatcher dispatcher; |
| 27 | + private final NotificationRepository notificationRepository; |
| 28 | + private final FcmTokenRepository fcmTokenRepository; |
| 29 | + private final UserRepository userRepository; |
| 30 | + |
| 31 | + /** |
| 32 | + * 서비스로 어디서든 한 줄로 알림 발송 가능 |
| 33 | + */ |
| 34 | + @Transactional |
| 35 | + public void send(Long receiverId, NotificationType type, Map<String, Object> params) { |
| 36 | + // 1. 받는 사람 검증 |
| 37 | + if (!userRepository.existsById(receiverId)) { |
| 38 | + throw new GeneralException(ErrorStatus.USER_NOT_FOUND); |
| 39 | + } |
| 40 | + |
| 41 | + // 2. 파라미터 검증 (NotificationType별 필수 키) |
| 42 | + type.validate(params); |
| 43 | + |
| 44 | + // 3. 템플릿 처리 |
| 45 | + String title = type.formatTitle(params); |
| 46 | + String body = type.formatBody(params); |
| 47 | + |
| 48 | + // 4. 이력 저장 |
| 49 | + Notification notification = notificationRepository.save( |
| 50 | + Notification.create(receiverId, type, title, body, params) |
| 51 | + ); |
| 52 | + |
| 53 | + // 5. 토큰 조회, 없으면 정상 종료 (유저가 알림 거부/로그아웃 등 정상 케이스) |
| 54 | + List<String> tokens = fcmTokenRepository.findAllByUserId(receiverId).stream() |
| 55 | + .map(FcmToken::getToken) |
| 56 | + .toList(); |
| 57 | + |
| 58 | + if (tokens.isEmpty()) { |
| 59 | + log.info("발송 대상 토큰 없음 (userId={}, type={})", receiverId, type); |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + // 6. 비동기 발송 위임 |
| 64 | + dispatcher.dispatch(new NotificationDispatchCommand( |
| 65 | + notification.getId(), |
| 66 | + receiverId, |
| 67 | + type, |
| 68 | + title, |
| 69 | + body, |
| 70 | + params, |
| 71 | + tokens |
| 72 | + )); |
| 73 | + } |
| 74 | +} |
0 commit comments