Notification 엔티티 수정
Notification 엔티티에 알림의 대상이 되는 객체의 ID를 저장할 수 있는 typeId 필드를 추가합니다. 이 필드는 좋아요, 댓글, 팔로우 등의 구체적인 대상을 식별합니다.
@Column(name = "type_id")
private Long typeId;
NotificationController 구현
NotificationController에 사용자별 알림 목록을 조회하는 엔드포인트를 추가합니다. 사용자 ID는 토큰 컨텍스트에서 추출합니다.
@RestController
@RequestMapping("/api/noti")
@RequiredArgsConstructor
public class NotificationController {
private final NotificationService notificationService;
@GetMapping
public List<NotificationDto> getNotis() {
TokenContext context = TokenContextHolder.getContext();
Long userId = context.getUserId();
return notificationService.getNotis(userId);
}
}
NotificationDto 수정
NotificationDto는 알림 정보를 전달하기 위한 DTO입니다. 알림 메시지와 생성 시간을 포함합니다.
public static NotificationDto getMyNotification(Notification notification) {
String message = "";
message += notification.getFromUser().getName();
message += "님이 ";
if (notification.getType().equals(COMMENT)) message += "포스트에 댓글을 남겼습니다.";
if (notification.getType().equals(LIKE)) message += "포스트를 좋아합니다.";
if (notification.getType().equals(FOLLOW)) message += "당신을 팔로우 합니다.";
return new NotificationDto(message, notification.getCreatedAt());
}
NotificationRepository 수정
NotificationRepository에서는 알림을 저장하는 mSave 메소드를 정의합니다. 이 메소드는 알림의 발생 주체, 대상 사용자, 알림 유형, 대상 객체 ID를 매개변수로 받습니다.
@Query(value = "INSERT INTO notifications(from_user_id, to_user_id, type, type_id, created_at) VALUES(?1, ?2, ?3, ?4, now())", nativeQuery = true)
int mSave(Long fromUserId, Long toUserId, String type, Long typeId);
각 서비스에서 알림 생성
좋아요, 댓글, 팔로우 등의 서비스에서는 알림을 생성할 때 NotificationRepository의 mSave 메소드를 호출하여 알림을 저장합니다.
notificationRepository.mSave(followerId, followingId, NotiType.FOLLOW.name(), follow.getId());
notificationRepository.mSave(userId, post.getUser().getId(), NotiType.LIKE.name(), postId);
notificationRepository.mSave(userId, post.getUser().getId(), NotiType.COMMENT.name(), postId);
NotificationService 구현
NotificationService에서는 사용자별로 알림 목록을 조회하는 로직을 구현합니다. 본인에게 발생한 알림은 제외하고, 조회 결과를 생성 시간의 내림차순으로 정렬합니다.
@Service
@RequiredArgsConstructor
public class NotificationService {
private final NotificationRepository notificationRepository;
@Transactional(readOnly = true)
public List<NotificationDto> getNotis(Long userId) {
List<Notification> notis = new ArrayList<>();
if (notificationRepository.existsByToUserId(userId)) { // notification
List<Notification> notifications = notificationRepository.findByToUserId(userId);
for (Notification noti : notifications) {
if (!noti.getFromUser().getId().equals(userId)) { // 본인 제외
notis.add(noti);
}
}
}
return notis.stream()
.map(NotificationDto::getMyNotification)
.sorted(Comparator.comparing(NotificationDto::getCreatedAt).reversed())
.collect(Collectors.toList());
}
}
결론
이 구현을 통해 사용자는 다른 사용자의 활동(좋아요, 댓글, 팔로우)에 대한 알림을 받을 수 있으며, 커뮤니티 내에서의 상호작용을 증진할 수 있습니다.
'프로젝트 (Java) > 예약마켓' 카테고리의 다른 글
[프로젝트] 24. JWT 수정 및 Redis 연동을 통한 로그아웃 기능 구현 (0) | 2024.01.29 |
---|---|
[프로젝트] 23. 로그아웃 기능을 위한 Redis 추가 (0) | 2024.01.29 |
[프로젝트] 21. 뉴스피드 알림 기능 추가 (0) | 2024.01.29 |
[프로젝트] 20. 뉴스피드 기능 추가 (0) | 2024.01.29 |
[프로젝트] 19. 연관관계 매핑을 통한 회원 탈퇴 기능 (0) | 2024.01.27 |