Skip to content

Commit

Permalink
Merge pull request #139 from minseok1015/add2
Browse files Browse the repository at this point in the history
add
  • Loading branch information
minseok1015 authored Aug 19, 2024
2 parents 6e51de0 + 1b72591 commit 8bcc31c
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 6 deletions.
4 changes: 2 additions & 2 deletions src/main/java/store/itpick/backend/config/WebConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtAuthenticationInterceptor)
.order(1)
.addPathPatterns("/**")
.excludePathPatterns("/auth/login", "/auth/signup", "/auth/refresh","/auth/emails/**", "/rank/**","/auth/email/check","/auth/nickname/check","/favicon.ico","/keyword/**","/debate/keyword", "/test/**");
.excludePathPatterns("/auth/login", "/auth/signup", "/auth/refresh","/auth/emails/**", "/rank/**","/auth/email/check","/auth/nickname/check","/favicon.ico","/keyword/**","/debate/keyword", "/test/**","/debate/trend");
//인터셉터 적용 범위 수정
registry.addInterceptor(getJwtInterceptor)
.addPathPatterns("/user/email");
Expand All @@ -47,7 +47,7 @@ public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers)
public void addCorsMappings(CorsRegistry registry) {
log.info("CorsMapping이 호출 되었습니다.");
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000", "http://localhost:5173", "https://localhost:5173", "https://itpick.netlify.app","https://itpick.vercel.app","https://deploy-preview-85--itpick.netlify.app")
.allowedOrigins("http://localhost:3000", "http://localhost:5173", "https://localhost:5173", "https://itpick.netlify.app","https://itpick.vercel.app","https://deploy-preview-85--itpick.netlify.app","https://deploy-preview-99--itpick.netlify.app")
.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH","OPTIONS")
.exposedHeaders("location", "Authorization")
.allowedHeaders("Content-Type", "Authorization", "X-Requested-With", "Accept")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,12 @@ public BaseResponse<?> deleteDebate(@PreAuthorize long userId, @PathVariable Lon
debateService.deleteDebate(debateId,userId);
return new BaseResponse<>(null);
}


@GetMapping("/trend")
public BaseResponse<List<DebateByKeywordDTO>> getTrendDebate(){
List<DebateByKeywordDTO> debateResponse = debateService.getHotDebate();

return new BaseResponse<>(debateResponse);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
@Getter
public class DebateByKeywordDTO {
String title;
String content;
Long debateId;
String mediaUrl;
Long hit;
Long comment;
Expand Down
28 changes: 28 additions & 0 deletions src/main/java/store/itpick/backend/model/TrendDebate.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package store.itpick.backend.model;


import jakarta.persistence.*;
import lombok.*;

import java.sql.Timestamp;

@Entity
@Table(name = "trend_debate")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class TrendDebate {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "trend_debate_id")
private Long trendDebateId;

@OneToOne
@JoinColumn(name = "debate_id", nullable = false)
private Debate debate;

@Column(name = "update_at", nullable = false)
private Timestamp updateAt;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package store.itpick.backend.repository;

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;
Expand All @@ -8,6 +9,7 @@
import store.itpick.backend.model.Debate;
import store.itpick.backend.model.User;

import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;

Expand Down Expand Up @@ -38,5 +40,10 @@ public interface DebateRepository extends JpaRepository<Debate, Long> {

Optional<Debate> getDebateByDebateId(Long debateId);

@Query("SELECT d FROM Debate d " +
"WHERE d.createAt >= :startTime " +
"ORDER BY d.hits DESC")
List<Debate> findTop3DebatesCreatedInLast3Days(@Param("startTime") Timestamp startTime, Pageable pageable);


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package store.itpick.backend.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import store.itpick.backend.model.TrendDebate;

@Repository
public interface TrendDebateRepository extends JpaRepository<TrendDebate, Long> {
void deleteAll();
}
60 changes: 57 additions & 3 deletions src/main/java/store/itpick/backend/service/DebateService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import store.itpick.backend.common.exception.DebateException;
import store.itpick.backend.common.exception.AuthException;
Expand Down Expand Up @@ -41,6 +42,7 @@ public class DebateService {
private final JwtProvider jwtProvider;
private final S3ImageBucketService s3ImageBucketService;
private final RecentViewedDebateRepository recentViewedDebateRepository;
private final TrendDebateRepository trendDebateRepository;

@Transactional
public PostDebateResponse createDebate(PostDebateRequest postDebateRequest, long userId) {
Expand Down Expand Up @@ -230,11 +232,11 @@ public List<DebateByKeywordDTO> GetDebatesByKeyword(Long keywordID, String sort)
for (Debate debate : debates) {
if(debate.getStatus().equals("active")){
String title= debate.getTitle();
String content =debate.getContent();
Long debateId =debate.getDebateId();
String mediaUrl =debate.getImageUrl();
Long hit = debate.getHits();
Long comment = (long) debate.getComment().size();
debateList.add(new DebateByKeywordDTO(title,content,mediaUrl,hit,comment));
debateList.add(new DebateByKeywordDTO(title,debateId,mediaUrl,hit,comment));
}
}

Expand Down Expand Up @@ -267,7 +269,7 @@ public List<DebateByKeywordDTO> getRecentViewedDebate(long userId){
// Debate를 DTO로 변환
return debates.stream()
.filter(debate -> "active".equals(debate.getStatus()))
.map(debate -> new DebateByKeywordDTO(debate.getTitle(), debate.getContent(), debate.getImageUrl(),debate.getHits(), (long) debate.getComment().size()))
.map(debate -> new DebateByKeywordDTO(debate.getTitle(), debate.getDebateId(), debate.getImageUrl(),debate.getHits(), (long) debate.getComment().size()))
.collect(Collectors.toList());

}
Expand All @@ -294,4 +296,56 @@ public void deleteDebate(Long debateId, long userId) {

}

@Transactional
public void updateHotDebate() {
// 현재 시간 및 48시간 전 시간 계산
Timestamp endTime = new Timestamp(System.currentTimeMillis());
Timestamp startTime = new Timestamp(endTime.getTime() - 3 * 24 * 60 * 60 * 1000); // 3일 전 시간
PageRequest pageRequest = PageRequest.of(0, 3); // 상위 3개만 가져오기

// 기존의 TrendDebate 삭제
trendDebateRepository.deleteAllInBatch();

// 48시간 동안 조회수가 가장 많이 오른 상위 3개의 Debate 조회
List<Debate> debateList = debateRepository.findTop3DebatesCreatedInLast3Days(startTime, pageRequest);

// 새로운 TrendDebate 엔트리 삽입
for (Debate debate : debateList) {
TrendDebate trendDebate = TrendDebate.builder()
.debate(debate)
.updateAt(endTime) // 업데이트된 시간 저장
.build();

trendDebateRepository.save(trendDebate);

}

}

@Transactional
public List<DebateByKeywordDTO> getHotDebate() {

// TrendDebate 테이블에서 현재 저장된 Debate 3개를 가져옵니다.
List<TrendDebate> trendDebates = trendDebateRepository.findAll();

// DebateByKeywordDTO 리스트 초기화
List<DebateByKeywordDTO> debates = new ArrayList<>();

// TrendDebate에 있는 Debate를 DebateByKeywordDTO로 변환하여 리스트에 추가
for (TrendDebate trendDebate : trendDebates) {
Debate debate = trendDebate.getDebate();
DebateByKeywordDTO debateDTO = new DebateByKeywordDTO(
debate.getTitle(),
debate.getDebateId(),
debate.getImageUrl(),
debate.getHits(),
(long) debate.getComment().size()
);
debates.add(debateDTO);
}

// 최종 리스트 반환
return debates;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public class SchedulerService {

private final SeleniumService seleniumService;
private final KeywordService keywordService;
private final DebateService debateService;
private final Redis redis;


Expand Down Expand Up @@ -147,4 +148,9 @@ public void performWeeklyTasks() {
log.info("Weekly task completed.");
}

@Scheduled(cron = "0 30 * * * *")
public void updateTrendDebate(){
debateService.updateHotDebate();
}

}

0 comments on commit 8bcc31c

Please sign in to comment.