-
Notifications
You must be signed in to change notification settings - Fork 2
[FEAT] 알림 도메인 api 구현 #54
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
b388fc5
feat: 알림 조회 API 기본 구조 구현 (#34)
rkdehdrbs7885-oss f8ba0ea
Merge branch 'develop' into feat/#34-notification-api
rkdehdrbs7885-oss 6691063
Merge remote-tracking branch 'origin/develop' into feat/#34-notificat…
rkdehdrbs7885-oss ac3429e
feat: 알림 도메인 기본 api 구현 (#34)
rkdehdrbs7885-oss 933fc34
refactor: 코드 래빗 수정_1 (#34)
rkdehdrbs7885-oss 716187b
refactor: 팀 리뷰 수정_1 (#34)
rkdehdrbs7885-oss 1bde744
feat: 테스트 코드 추가 (#34)
rkdehdrbs7885-oss aaf151b
feat: 알림 이벤트 추가 (#34)
rkdehdrbs7885-oss daa94ae
refactor: 코드 래빗 수정_2 (#34)
rkdehdrbs7885-oss 982f6e1
Merge remote-tracking branch 'origin/develop' into feat/#34-notificat…
rkdehdrbs7885-oss 3891ce7
Merge remote-tracking branch 'origin/develop' into feat/#34-notificat…
rkdehdrbs7885-oss 0ae66ad
refactor: 팀 리뷰 수정_2 (#34)
rkdehdrbs7885-oss File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
63 changes: 63 additions & 0 deletions
63
src/main/java/com/mr/domain/notification/controller/NotificationController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| package com.mr.domain.notification.controller; | ||
|
|
||
| import com.mr.domain.notification.dto.res.NotificationListResponseDTO; | ||
| import com.mr.domain.notification.service.NotificationService; | ||
| import com.mr.global.apipayload.ApiResponse; | ||
| import com.mr.global.security.principal.CustomUserDetails; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.data.domain.Pageable; | ||
| import org.springframework.data.domain.Sort; | ||
| import org.springframework.data.web.PageableDefault; | ||
| import org.springframework.security.core.annotation.AuthenticationPrincipal; | ||
| import org.springframework.web.bind.annotation.GetMapping; | ||
| import org.springframework.web.bind.annotation.PatchMapping; | ||
| import org.springframework.web.bind.annotation.PathVariable; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/api/notifications") | ||
| @RequiredArgsConstructor | ||
| public class NotificationController { | ||
|
|
||
| private final NotificationService notificationService; | ||
|
|
||
| @GetMapping | ||
| public ApiResponse<NotificationListResponseDTO> getNotifications( | ||
| @AuthenticationPrincipal CustomUserDetails userDetails, | ||
| @PageableDefault(page = 0, size = 10, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable | ||
| ){ | ||
| Long userId = userDetails.getUserId(); | ||
| NotificationListResponseDTO result = notificationService.getNotificationList(userId, pageable); | ||
| return ApiResponse.onSuccess(result); | ||
| } | ||
|
|
||
| // 알림 읽음 처리 | ||
| @PatchMapping("/{notificationId}/read") | ||
| public ApiResponse<Void> readNotification( | ||
| @AuthenticationPrincipal CustomUserDetails userDetails, | ||
| @PathVariable Long notificationId | ||
| ) { | ||
| Long userId = userDetails.getUserId(); | ||
| notificationService.readNotification(userId, notificationId); | ||
| return ApiResponse.onSuccess(null); | ||
| } | ||
|
|
||
| // 알림 전체 읽음 처리 | ||
| @PatchMapping("/read-all") | ||
| public ApiResponse<Void> readAllNotifications( | ||
| @AuthenticationPrincipal CustomUserDetails userDetails | ||
| ) { | ||
| notificationService.readAllNotifications(userDetails.getUserId()); | ||
| return ApiResponse.onSuccess(null); | ||
| } | ||
|
|
||
| // 안 읽은 알림 여부 확인 (사이드바 뱃지용) | ||
| @GetMapping("/unread-status") | ||
| public ApiResponse<Boolean> checkUnreadStatus( | ||
| @AuthenticationPrincipal CustomUserDetails userDetails | ||
| ) { | ||
| boolean hasUnread = notificationService.checkUnreadNotification(userDetails.getUserId()); | ||
| return ApiResponse.onSuccess(hasUnread); | ||
| } | ||
| } |
38 changes: 38 additions & 0 deletions
38
src/main/java/com/mr/domain/notification/dto/res/NotificationListResponseDTO.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| package com.mr.domain.notification.dto.res; | ||
|
|
||
| import com.mr.domain.notification.entity.Notification; | ||
| import lombok.AllArgsConstructor; | ||
| import lombok.Builder; | ||
| import lombok.Getter; | ||
| import lombok.NoArgsConstructor; | ||
| import org.springframework.data.domain.Page; | ||
| import org.springframework.data.domain.Slice; | ||
|
|
||
| import java.util.List; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| @Getter | ||
| @Builder | ||
| @NoArgsConstructor | ||
| @AllArgsConstructor | ||
| public class NotificationListResponseDTO { | ||
| private List<NotificationResponseDTO> notificationList; | ||
| private Integer listSize; | ||
| private Boolean hasNext; | ||
| private Boolean isFirst; | ||
| private Boolean isLast; | ||
|
|
||
| public static NotificationListResponseDTO of(Slice<Notification> notificationSlice) { | ||
| List<NotificationResponseDTO> notificationDTOList = notificationSlice.getContent().stream() | ||
| .map(NotificationResponseDTO::from) | ||
| .collect(Collectors.toList()); | ||
|
|
||
| return NotificationListResponseDTO.builder() | ||
| .notificationList(notificationDTOList) | ||
| .listSize(notificationDTOList.size()) | ||
| .hasNext(notificationSlice.hasNext()) | ||
| .isFirst(notificationSlice.isFirst()) | ||
| .isLast(notificationSlice.isLast()) | ||
| .build(); | ||
| } | ||
| } |
32 changes: 32 additions & 0 deletions
32
src/main/java/com/mr/domain/notification/dto/res/NotificationResponseDTO.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| package com.mr.domain.notification.dto.res; | ||
|
|
||
| import com.mr.domain.notification.entity.Notification; | ||
| import lombok.AllArgsConstructor; | ||
| import lombok.Builder; | ||
| import lombok.Getter; | ||
| import lombok.NoArgsConstructor; | ||
|
|
||
| import java.time.LocalDateTime; | ||
|
|
||
| @Getter | ||
| @Builder | ||
| @NoArgsConstructor | ||
| @AllArgsConstructor | ||
| public class NotificationResponseDTO { | ||
|
|
||
| private Long notificationId; | ||
| private String title; | ||
| private String content; | ||
| private Boolean isRead; | ||
| private LocalDateTime createdAt; | ||
|
|
||
| public static NotificationResponseDTO from(Notification notification) { | ||
| return NotificationResponseDTO.builder() | ||
| .notificationId(notification.getId()) | ||
| .title(notification.getTitle()) | ||
| .content(notification.getContent()) | ||
| .isRead(notification.isRead()) | ||
| .createdAt(notification.getCreatedAt()) | ||
| .build(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 changes: 21 additions & 0 deletions
21
src/main/java/com/mr/domain/notification/exception/NotificationErrorStatus.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| package com.mr.domain.notification.exception; | ||
|
|
||
| import com.mr.global.apipayload.code.BaseCode; | ||
| import lombok.AllArgsConstructor; | ||
| import lombok.Getter; | ||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| @Getter | ||
| @AllArgsConstructor | ||
| public enum NotificationErrorStatus implements BaseCode { | ||
|
|
||
| // [403] 권한 에러 | ||
| FORBIDDEN_NOTIFICATION(HttpStatus.FORBIDDEN, "NOTIFICATION_403_01", "해당 알림에 대한 권한이 없습니다."), | ||
|
|
||
| // [404] 리소스 없음 | ||
| NOTIFICATION_NOT_FOUND(HttpStatus.NOT_FOUND, "NOTIFICATION_404_01", "존재하지 않는 알림입니다."); | ||
|
|
||
| private final HttpStatus status; | ||
| private final String code; | ||
| private final String message; | ||
| } |
29 changes: 29 additions & 0 deletions
29
src/main/java/com/mr/domain/notification/repository/NotificationRepository.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| package com.mr.domain.notification.repository; | ||
|
|
||
| import com.mr.domain.notification.entity.Notification; | ||
| import org.springframework.data.domain.Page; | ||
| import org.springframework.data.domain.Pageable; | ||
| import org.springframework.data.jpa.repository.JpaRepository; | ||
| import org.springframework.data.jpa.repository.Modifying; | ||
| import org.springframework.data.jpa.repository.Query; | ||
| import org.springframework.data.repository.query.Param; | ||
|
|
||
| import java.time.LocalDateTime; | ||
| import java.util.Optional; | ||
|
|
||
| public interface NotificationRepository extends JpaRepository<Notification, Long> { | ||
|
|
||
| Page<Notification> findAllByUser_UserIdAndDeletedAtIsNull(Long userId, Pageable pageable); | ||
|
|
||
| Optional<Notification> findByIdAndDeletedAtIsNull(Long id); | ||
|
|
||
| @Modifying(clearAutomatically = true) | ||
| @Query("update Notification n set n.isRead = true where n.user.userId = :userId and n.isRead = false and n.deletedAt is null") | ||
| void bulkMarkAllAsReadByUserId(@Param("userId") Long userId); | ||
|
|
||
| // 유저에게 안 읽은 알림이 단 하나라도 존재하는지 확인 (사이드바 종 아이콘 뱃지용) | ||
| boolean existsByUser_UserIdAndIsReadFalseAndDeletedAtIsNull(Long userId); | ||
|
|
||
| // 중복 알림 방지용 쿼리 메서드 | ||
| boolean existsByUser_UserIdAndTitleAndCreatedAtAfter(Long userId, String title, LocalDateTime time); | ||
| } |
69 changes: 69 additions & 0 deletions
69
src/main/java/com/mr/domain/notification/service/NotificationEventListener.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| package com.mr.domain.notification.service; | ||
|
|
||
| import com.mr.domain.notification.entity.Notification; | ||
| import com.mr.domain.notification.repository.NotificationRepository; | ||
| import com.mr.domain.user.entity.User; | ||
| import com.mr.domain.user.exception.UserErrorStatus; | ||
| import com.mr.domain.user.repository.UserRepository; | ||
| import com.mr.global.apipayload.exception.GeneralException; | ||
| import com.mr.global.event.NotificationEvent; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.retry.annotation.Backoff; | ||
| import org.springframework.retry.annotation.Recover; | ||
| import org.springframework.retry.annotation.Retryable; | ||
| import org.springframework.scheduling.annotation.Async; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
| import org.springframework.transaction.event.TransactionPhase; | ||
| import org.springframework.transaction.event.TransactionalEventListener; | ||
|
|
||
| import java.time.LocalDateTime; | ||
|
|
||
| @Slf4j | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class NotificationEventListener { | ||
|
|
||
| private final NotificationRepository notificationRepository; | ||
| private final UserRepository userRepository; | ||
|
|
||
| //누군가 NotificationEvent를 발행하면 이 메서드가 자동으로 실행 | ||
| // DB 저장 실패 시 최대 3번 재시도 (1초 간격) | ||
| @Retryable( | ||
| retryFor = {Exception.class}, | ||
| maxAttempts = 3, | ||
| backoff = @Backoff(delay = 1000) | ||
| ) | ||
| @Async | ||
| @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) // 메인 트랜잭션이 커밋된(AFTER_COMMIT) 이후에만 알림을 저장하도록 변경 | ||
| @Transactional | ||
| public void handleNotificationEvent(NotificationEvent event) { | ||
|
rkdehdrbs7885-oss marked this conversation as resolved.
|
||
|
|
||
| // 중복 알림 검증 로직 (1분 이내 동일 제목 알림 무시) | ||
| LocalDateTime oneMinuteAgo = LocalDateTime.now().minusMinutes(1); | ||
| if (notificationRepository.existsByUser_UserIdAndTitleAndCreatedAtAfter( | ||
| event.getUserId(), event.getTitle(), oneMinuteAgo)) { | ||
| return; // 걸리면 바로 종료 | ||
| } | ||
|
|
||
| User user = userRepository.findById(event.getUserId()) | ||
| .orElseThrow(() -> new GeneralException(UserErrorStatus.USER_NOT_FOUND)); | ||
|
|
||
| Notification notification = Notification.create( | ||
| user, | ||
| event.getTitle(), | ||
| event.getContent() | ||
| ); | ||
|
|
||
| notificationRepository.save(notification); | ||
|
rkdehdrbs7885-oss marked this conversation as resolved.
|
||
| } | ||
|
|
||
| // 3번의 재시도 전부 실패했을 때 실행되는 '영구 보정 경로(Fallback)' | ||
| @Recover | ||
| public void recoverNotificationEvent(Exception e, NotificationEvent event) { | ||
| // 나중에 이 로그를 수집해서 슬랙 알림을 보내거나, 수동으로 복구할 수 있도록 단서를 남김 | ||
| log.error("[알림 저장 최종 실패] userId: {}, title: {}, 원인: {}", | ||
| event.getUserId(), event.getTitle(), e.getMessage()); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.