Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/alarm")
Expand All @@ -29,4 +30,11 @@ public ResponseEntity<List<NotificationResponseDto>> getLikeAlarms() {
Long userId = SecurityUtil.getCurrentUserId();
return ResponseEntity.ok(notificationService.getLikeAlarms(userId));
}

@GetMapping("/unread-count")
public ResponseEntity<Map<String, Long>> getUnreadCount() {
Long userId = SecurityUtil.getCurrentUserId();
long count = notificationService.getUnreadCount(userId);
return ResponseEntity.ok(Map.of("unreadCount", count));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ List<Notification> findByReceiverIdAndTypeOrderByCreatedAtDesc(
NotificationType type
);

long countByReceiverIdAndIsReadFalse(Long receiverId);

void deleteAllByReceiverId(Long receiverId);

void deleteAllBySenderId(Long senderId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,38 @@ public class NotificationService {
private final UserRepository userRepository;
private final CommentRepository commentRepository;

@Transactional
public List<NotificationResponseDto> getCommentAlarms(Long userId) {
List<Notification> notifications = notificationRepository
.findByReceiverIdAndTypeOrderByCreatedAtDesc(userId, NotificationType.COMMENT);

markAsRead(notifications);

return toResponseDtos(notifications);
}

@Transactional
public List<NotificationResponseDto> getLikeAlarms(Long userId) {
List<Notification> notifications = notificationRepository
.findByReceiverIdAndTypeOrderByCreatedAtDesc(userId, NotificationType.LIKE);

markAsRead(notifications);

return toResponseDtos(notifications);
}

// 헤더에 표시할 안 읽은 알림 개수
public long getUnreadCount(Long userId) {
return notificationRepository.countByReceiverIdAndIsReadFalse(userId);
}

// 조회한 알림들 읽음 처리 (더티체킹으로 자동 반영)
private void markAsRead(List<Notification> notifications) {
notifications.stream()
.filter(notification -> !notification.isRead())
.forEach(Notification::markAsRead);
}

// 알림 목록의 senderId, commentId를 모아 각각 한 번에 조회한 뒤 DTO로 변환 (N+1 방지)
private List<NotificationResponseDto> toResponseDtos(List<Notification> notifications) {
List<Long> senderIds = notifications.stream()
Expand Down
Loading