team-forAdhd / forAdhd-server

For ADHD 서버
1 stars 2 forks source link

게시글 및 댓글 수정사항 반영 #47

Closed newoceanwave closed 1 month ago

newoceanwave commented 2 months ago

💻 구현 내용

🛠️ 개발 오류 사항

1. notification.java `@Getter @NoArgsConstructor @AllArgsConstructor @Builder(toBuilder = true) @Table(name = "notification") public class Notification { @jakarta.persistence.Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;

private String userId;

private String message;

private boolean isRead;

@JsonSerialize(using = LocalDateTimeToEpochSecondSerializer.class)
private LocalDateTime createdAt;

} `

2. NotificationServiceImpl

@Service
@RequiredArgsConstructor
public class NotificationServiceImpl implements NotificationService {
    private final NotificationRepository notificationRepository;
    private final SseEmitters sseEmitters;

    @Override
    public void createNotification(String userId, String message) {
        Notification notification = Notification.builder()
                .userId(userId)
                .message(message)
                .isRead(false)
                .createdAt(LocalDateTime.now())
                .build();
        notificationRepository.save(notification);
        sseEmitters.sendNotification(userId, message);
    }

    @Override
    public List<Notification> getNotifications(String userId) {
        return notificationRepository.findByUserIdOrderByCreatedAtDesc(userId);
    }

    @Override
    @Transactional
    public void markAsRead(Long notificationId) {
        Notification notification = notificationRepository.findById(notificationId)
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_NOTIFICATION));

        Notification updatedNotification = notification.toBuilder()
                .isRead(true)
                .build();

        notificationRepository.save(updatedNotification);
    }
}

3. notificationcontroller `@RestController @RequestMapping("/api/v1/notifications") @RequiredArgsConstructor @CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8080"}) public class NotificationController { private final NotificationService notificationService; private final SseEmitters sseEmitters;

@GetMapping("/sse")
public SseEmitter streamSseMvc(@RequestParam String userId) {
    SseEmitter emitter = new SseEmitter(0L);
    sseEmitters.addEmitter(userId, emitter);
    emitter.onCompletion(() -> sseEmitters.removeEmitter(userId, emitter));
    emitter.onTimeout(() -> sseEmitters.removeEmitter(userId, emitter));
    emitter.onError((e) -> sseEmitters.removeEmitter(userId, emitter));
    return emitter;
}

@PostMapping("/mark-as-read/{id}")
public ResponseEntity<Void> markAsRead(@PathVariable Long id) {
    notificationService.markAsRead(id);
    return ResponseEntity.ok().build();
}

} `

4. SseEmitters `@Component public class SseEmitters { private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();

public synchronized void addEmitter(String userId, SseEmitter emitter) {
    emitters.put(userId, emitter);
}

public synchronized void removeEmitter(String userId, SseEmitter emitter) {
    emitters.remove(userId, emitter);
}

public void sendNotification(String userId, String message) {
    SseEmitter emitter = emitters.get(userId);
    if (emitter != null) {
        try {
            emitter.send(SseEmitter.event().name("notification").data(message));
        } catch (IOException e) {
            removeEmitter(userId, emitter);
        }
    }
}

} `

이와 관련해서 CORS 에러가 발생했어서, webconfigsecurityconfig에 다음과 같은 내용 추가하였습니다. @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("http://localhost:3000", "http://localhost:8080") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } } @RequiredArgsConstructor @EnableWebSecurity @Configuration public class SecurityConfig { @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOriginPatterns(Arrays.asList("http://localhost:3000", "http://localhost:8080")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(Arrays.asList("*")); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }

🗣️ For 리뷰어

close #42

jkde7721 commented 1 month ago

https://github.com/team-forAdhd/forAdhd-server/pull/47#pullrequestreview-2208876521

@newoceanwave 수정 완료했는데 제가 발견을 못한거라면 죄송해요 한번더 확인 부탁드려요!