Skip to content

Commit

Permalink
Merge pull request #41 from Itstime-replog/feature/#40
Browse files Browse the repository at this point in the history
Feature : 커뮤니티 게시물 좋아요 API 구현
  • Loading branch information
jeong724 authored Jan 6, 2025
2 parents 0442bc4 + b90f2dd commit 086c322
Show file tree
Hide file tree
Showing 11 changed files with 309 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ public enum ErrorStatus implements BaseErrorCode {
// Community 관련 에러
_COMMUNITY_NOT_FOUND(HttpStatus.NOT_FOUND, "COMMUNITY404", "해당 커뮤니티 게시글을 찾을 수 없습니다."),

//PostLike 관련 에러
_POSTLIKE_BAD_REQUEST(HttpStatus.BAD_REQUEST, "POSTLIKE400", "올바른 PostType을 입력해주세요."),
// comment 관련 에러
_COMMENT_NOT_FOUND(HttpStatus.NOT_FOUND, "COMMENT404", "해당 댓글을 찾을 수 없습니다."),
_PARENT_COMMENT_NOT_FOUND(HttpStatus.NOT_FOUND, "COMMENT404", "해당 부모 댓글을 찾을 수 없습니다.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.List;
import java.util.UUID;

import itstime.reflog.postlike.service.PostLikeService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
Expand All @@ -23,6 +24,7 @@
public class CommunityController {
private final CommunityService communityService;
private final AmazonS3Manager amazonS3Manager;
private final PostLikeService postLikeService;

@Operation(
summary = "커뮤니티 파일 임시 생성 API",
Expand Down Expand Up @@ -174,11 +176,11 @@ public ResponseEntity<CommonApiResponse<Void>> deleteCommunity(
)
@GetMapping("/filter")
public ResponseEntity<CommonApiResponse<List<CommunityDto.CombinedCategoryResponse>>> getFilteredCommunity(
@RequestParam(required = false) List<String> postTypes,
@RequestParam(required = false) List<String> learningTypes
) {
List<CommunityDto.CombinedCategoryResponse> responses = communityService.getFilteredCommunity(postTypes,
learningTypes);
@RequestParam Long memberId,
@RequestParam(required = false) List<String> postTypes,
@RequestParam(required = false) List<String> learningTypes
){
List<CommunityDto.CombinedCategoryResponse> responses = communityService.getFilteredCommunity(memberId,postTypes, learningTypes);
return ResponseEntity.ok(CommonApiResponse.onSuccess(responses));
}

Expand All @@ -202,9 +204,40 @@ public ResponseEntity<CommonApiResponse<List<CommunityDto.CombinedCategoryRespon
)
@GetMapping("/search")
public ResponseEntity<CommonApiResponse<List<CommunityDto.CombinedCategoryResponse>>> getSearchedCommunity(
@RequestParam(required = false) String title
) {
List<CommunityDto.CombinedCategoryResponse> responses = communityService.getSearchedCommunity(title);
@RequestParam Long memberId,
@RequestParam String title
){
List<CommunityDto.CombinedCategoryResponse> responses = communityService.getSearchedCommunity(memberId,title);
return ResponseEntity.ok(CommonApiResponse.onSuccess(responses));
}

@Operation(
summary = "커뮤니티 게시물 좋아요 API",
description = "커뮤니티 게시글 좋아요 버튼 누를때 사용하는 API입니다. postType에는 회고일지일 경우에는 RETROSPECT, 커뮤니티 게시물일 경우에는 COMMUNITY를 보내주면 됩니다.",
responses = {
@ApiResponse(
responseCode = "200",
description = "커뮤니티 게시글 좋아요 성공"
),
@ApiResponse(
responseCode = "404",
description = "해당 회원을 찾을 수 없음"
),
@ApiResponse(
responseCode = "500",
description = "서버 에러"
)
}
)
@PostMapping("/like/{postId}")
public ResponseEntity<CommonApiResponse<Void>> togglePostLike(
@RequestParam Long memberId,
@PathVariable Long postId,
@RequestParam String postType
){
postLikeService.togglePostLike(memberId, postId, postType);
return ResponseEntity.ok(CommonApiResponse.onSuccess(null));
}


}
7 changes: 7 additions & 0 deletions src/main/java/itstime/reflog/community/domain/Community.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

import itstime.reflog.comment.domain.Comment;
import itstime.reflog.member.domain.Member;
import itstime.reflog.mypage.domain.MyPage;
import itstime.reflog.postlike.domain.PostLike;
import jakarta.persistence.*;
import jakarta.persistence.CascadeType;
import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
Expand All @@ -30,6 +33,7 @@
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public class Community {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Expand All @@ -55,6 +59,9 @@ public class Community {
@JoinColumn(name = "member_id", nullable = false)
private Member member;

@OneToMany(mappedBy = "community", cascade = CascadeType.ALL)
private List<PostLike> postLikes;

@OneToMany(mappedBy = "community", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
private List<Comment> comments = new ArrayList<>();

Expand Down
12 changes: 9 additions & 3 deletions src/main/java/itstime/reflog/community/dto/CommunityDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,20 +41,24 @@ public static class CombinedCategoryResponse {
private List<String> learningTypes;
private String writer;
private Integer progressLevel; // Retrospect 전용
private Integer understandingLevel; // Retrospect 전용
private Integer understandingLevel;// Retrospect 전용
private Boolean isLike;
private int totalLike;

public static CombinedCategoryResponse fromCommunity(Community community, String writer) {
public static CombinedCategoryResponse fromCommunity(Community community, String writer, Boolean isLike, Integer totalLike) {
return CombinedCategoryResponse.builder()
.title(community.getTitle())
.content(community.getContent())
.createdDate(community.getCreatedAt())
.postTypes(community.getPostTypes())
.learningTypes(community.getLearningTypes())
.isLike(isLike)
.totalLike(totalLike)
.writer(writer)
.build();
}

public static CombinedCategoryResponse fromRetrospect(Retrospect retrospect, String writer) {
public static CombinedCategoryResponse fromRetrospect(Retrospect retrospect, String writer, Boolean isLike, Integer totalLike) {
return CombinedCategoryResponse.builder()
.title(retrospect.getTitle())
.createdDate(retrospect.getCreatedDate().atStartOfDay())
Expand All @@ -64,6 +68,8 @@ public static CombinedCategoryResponse fromRetrospect(Retrospect retrospect, Str
.collect(Collectors.toList())) //String 리스트로 변환
.progressLevel(retrospect.getProgressLevel())
.understandingLevel(retrospect.getUnderstandingLevel())
.isLike(isLike)
.totalLike(totalLike)
.writer(writer)
.build();
}
Expand Down
102 changes: 71 additions & 31 deletions src/main/java/itstime/reflog/community/service/CommunityService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import java.util.List;
import java.util.stream.Collectors;

import itstime.reflog.postlike.domain.PostLike;
import itstime.reflog.postlike.repository.PostLikeRepository;
import itstime.reflog.postlike.service.PostLikeService;
import itstime.reflog.comment.domain.Comment;
import itstime.reflog.comment.dto.CommentDto;
import itstime.reflog.comment.repository.CommentRepository;
Expand Down Expand Up @@ -39,6 +42,8 @@ public class CommunityService {
private final MyPageRepository myPageRepository;
private final RetrospectRepository retrospectRepository;
private final CommentRepository commentRepository;
private final PostLikeService postLikeService;
private final PostLikeRepository postLikeRepository;

@Transactional
public void createCommunity(Long memberId, CommunityDto.CommunitySaveOrUpdateRequest dto) {
Expand Down Expand Up @@ -76,8 +81,9 @@ public void createCommunity(Long memberId, CommunityDto.CommunitySaveOrUpdateReq
}
});

communityRepository.save(community);
}
communityRepository.save(community);

}

@Transactional
public CommunityDto.CommunityResponse getCommunity(Long communityId) {
Expand Down Expand Up @@ -166,9 +172,12 @@ public void deleteCommunity(Long communityId) {
communityRepository.delete(community);
}

//커뮤니티 게시글 필터링
@Transactional
public List<CommunityDto.CombinedCategoryResponse> getFilteredCommunity(List<String> postTypes, List<String> learningTypes) {
//커뮤니티 게시글 필터링
@Transactional
public List<CommunityDto.CombinedCategoryResponse> getFilteredCommunity(Long memberId, List<String> postTypes, List<String> learningTypes) {

Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new GeneralException(ErrorStatus._MEMBER_NOT_FOUND));

List<Community> communities;

Expand All @@ -185,36 +194,54 @@ public List<CommunityDto.CombinedCategoryResponse> getFilteredCommunity(List<Str
communities = communityRepository.findByLearningTypesAndPostTypes(postTypes, learningTypes);
}

//커뮤니티 response형태로 반환
List<CommunityDto.CombinedCategoryResponse> responses = communities.stream()
.map(community -> {
String nickname = myPageRepository.findByMember(community.getMember())
.map(MyPage::getNickname)
.orElse("닉네임 없음");
return CommunityDto.CombinedCategoryResponse.fromCommunity(community, nickname);
})
.collect(Collectors.toList());

//글 유형에 회고일지가 있는 경우
if (postTypes != null && postTypes.contains("회고일지")) {
List<Retrospect> retrospects = retrospectRepository.findByVisibilityIsTrue();
List<CommunityDto.CombinedCategoryResponse> retrospectResponses = retrospects.stream()
.map(retrospect -> {
String nickname = myPageRepository.findByMember(retrospect.getMember())
.map(MyPage::getNickname)
.orElse("닉네임 없음");
return CommunityDto.CombinedCategoryResponse.fromRetrospect(retrospect, nickname);
})
.collect(Collectors.toList());
responses.addAll(retrospectResponses); // 두 리스트 합치기(회고일지, 커뮤니티)
}
//커뮤니티 response형태로 반환 닉네임 추가
List<CommunityDto.CombinedCategoryResponse> responses = communities.stream()
.map(community -> {
//마이페이지 레포지토리에서 닉네임 반환
String nickname = myPageRepository.findByMember(community.getMember())
.map(MyPage::getNickname)
.orElse("닉네임 없음");

//좋아요 있는지 없는지 플래그
Boolean isLike = postLikeRepository.findByMemberAndCommunity(member, community).isPresent();

//게시물마다 좋아요 총 갯수 반환
int totalLike = postLikeService.getSumCommunityPostLike(community);

return CommunityDto.CombinedCategoryResponse.fromCommunity(community, nickname, isLike, totalLike);
})
.collect(Collectors.toList());

//글 유형에 회고일지가 있는 경우
if (postTypes != null && postTypes.contains("회고일지")) {
List<Retrospect> retrospects = retrospectRepository.findByVisibilityIsTrue();
List<CommunityDto.CombinedCategoryResponse> retrospectResponses = retrospects.stream()
.map(retrospect -> {
String nickname = myPageRepository.findByMember(retrospect.getMember())
.map(MyPage::getNickname)
.orElse("닉네임 없음");

//좋아요 있는지 없는지 플래그
Boolean isLike = postLikeRepository.findByMemberAndRetrospect(member, retrospect).isPresent();

//게시물마다 좋아요 총 갯수 반환
int totalLike = postLikeService.getSumRetrospectPostLike(retrospect);

return CommunityDto.CombinedCategoryResponse.fromRetrospect(retrospect, nickname, isLike, totalLike);
})
.collect(Collectors.toList());
responses.addAll(retrospectResponses); // 두 리스트 합치기(회고일지, 커뮤니티)
}

return responses;
}

//커뮤니티 게시물 검색
@Transactional
public List<CommunityDto.CombinedCategoryResponse> getSearchedCommunity(String title){
public List<CommunityDto.CombinedCategoryResponse> getSearchedCommunity(Long memberId, String title){

Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new GeneralException(ErrorStatus._MEMBER_NOT_FOUND));

//커뮤니티 게시물 중 키워드가 일치하는 게시물 찾기
List<Community> communities= communityRepository.searchCommunitiesByTitleContaining(title);
Expand All @@ -224,7 +251,14 @@ public List<CommunityDto.CombinedCategoryResponse> getSearchedCommunity(String t
String nickname = myPageRepository.findByMember(community.getMember())
.map(MyPage::getNickname)
.orElse("닉네임 없음");
return CommunityDto.CombinedCategoryResponse.fromCommunity(community, nickname);

//좋아요 있는지 없는지 플래그
Boolean isLike = postLikeRepository.findByMemberAndCommunity(member, community).isPresent();

//게시물마다 좋아요 총 갯수 반환
int totalLike = postLikeService.getSumCommunityPostLike(community);

return CommunityDto.CombinedCategoryResponse.fromCommunity(community, nickname, isLike, totalLike);
})
.collect(Collectors.toList());

Expand All @@ -236,7 +270,13 @@ public List<CommunityDto.CombinedCategoryResponse> getSearchedCommunity(String t
String nickname = myPageRepository.findByMember(retrospect.getMember())
.map(MyPage::getNickname)
.orElse("닉네임 없음");
return CommunityDto.CombinedCategoryResponse.fromRetrospect(retrospect, nickname);
//좋아요 있는지 없는지 플래그
Boolean isLike = postLikeRepository.findByMemberAndRetrospect(member, retrospect).isPresent();

//게시물마다 좋아요 총 갯수 반환
int totalLike = postLikeService.getSumRetrospectPostLike(retrospect);

return CommunityDto.CombinedCategoryResponse.fromRetrospect(retrospect, nickname, isLike, totalLike);
})
.collect(Collectors.toList());
responses.addAll(retrospectResponses); // 두 리스트 합치기(회고일지, 커뮤니티)
Expand Down
8 changes: 8 additions & 0 deletions src/main/java/itstime/reflog/member/domain/Member.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import java.util.List;

import itstime.reflog.analysis.domain.WeeklyAnalysis;
import itstime.reflog.comment.domain.Comment;
import itstime.reflog.commentLike.domain.CommentLike;
import itstime.reflog.community.domain.Community;
import itstime.reflog.goal.domain.DailyGoal;
import itstime.reflog.mypage.domain.MyPage;
import itstime.reflog.postlike.domain.PostLike;
import itstime.reflog.schedule.domain.Schedule;
import itstime.reflog.todolist.domain.Todolist;
import jakarta.persistence.*;
Expand Down Expand Up @@ -59,6 +61,12 @@ public class Member {
@OneToMany(mappedBy = "member", cascade = CascadeType.ALL)
private List<Community> communities;

@OneToMany(mappedBy = "member", cascade = CascadeType.ALL)
private List<PostLike> postLikes;

@OneToMany(mappedBy = "member", cascade = CascadeType.ALL)
private List<WeeklyAnalysis> weeklyAnalyses;

@OneToMany(mappedBy = "member", cascade = CascadeType.ALL)
private List<Comment> comments;

Expand Down
37 changes: 37 additions & 0 deletions src/main/java/itstime/reflog/postlike/domain/PostLike.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package itstime.reflog.postlike.domain;

import itstime.reflog.analysis.domain.enums.Period;
import itstime.reflog.community.domain.Community;
import itstime.reflog.member.domain.Member;
import itstime.reflog.postlike.domain.enums.PostType;
import itstime.reflog.retrospect.domain.Retrospect;
import jakarta.persistence.*;
import lombok.*;

@Entity
@Getter
@Builder
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public class PostLike {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id", nullable = false)
private Member member;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "community_id", nullable = true) //널 가능
private Community community;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "retrospect_id", nullable = true) //널 가능
private Retrospect retrospect;

@Enumerated(EnumType.STRING)
private PostType postType;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package itstime.reflog.postlike.domain.enums;

public enum PostType {
COMMUNITY, RETROSPECT
}
Loading

0 comments on commit 086c322

Please sign in to comment.