Skip to content

Commit

Permalink
Merge pull request #30 from KONKUK-MAP-Service/feat-spot
Browse files Browse the repository at this point in the history
✔️ [Fix] : 장소, 댓글 도메인 클라이언트 반환값 수정 #30
  • Loading branch information
evergreenn authored Apr 4, 2024
2 parents d47d608 + d8ccced commit 12f1cfc
Show file tree
Hide file tree
Showing 12 changed files with 152 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,17 +76,18 @@ public HttpResponse<CommentDeleteResponse> deleteComment(@PathVariable("spotId")
);
}

@GetMapping("/myAllComments/{pageNum}/{commentsInPage}")
@GetMapping("/myAllComments")
@Operation(summary = "자신의 댓글 전체 조회", description = "로그인한 사용자의 댓글을 전체 조회합니다.('페이지 위치:보여지는 댓글 수'형식으로 입력받습니다.)")
public HttpResponse<CommentPaginationResponse> allComments(@PathVariable("pageNum")Long pageNum, @PathVariable("commentsInPage")Long commentsInPage){
User user = commentService.getCurrentUser();
Long userId = user.getId(); //userId 정보
//List<SpotGetResponse> allSpots = spotService.getAllSpots(); //모든 spot 정보
List<CommentGetResponse> commentsByUser = commentService.getUserCommentsOfAllSpots(userId); //사용자가 쓴 comment만
//페이지 네이션 적용
CommentPaginationResponse commentPaginationResponses = commentService.getPagedComments(commentsByUser,pageNum, commentsInPage);
public HttpResponse<List<CommentListResponseDto>> allComments(@RequestParam(defaultValue = "1") int pageNumber,

@RequestParam(defaultValue = "10") int pageSize){

int adjustedPageNumber = pageNumber - 1;


List<CommentListResponseDto> pagedComments = commentService.getPagedComments(adjustedPageNumber, pageSize);
return HttpResponse.okBuild(
commentPaginationResponses);
pagedComments);
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public static CommentGetResponse of(Long commentNum, Comment comment,LocalDateTi
.commentId(comment.getId())
.comment(comment.getComment())
.userId(comment.getUser().getId())

.createDate(createDate)
.build();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.cona.KUsukKusuk.comment.dto;

import com.cona.KUsukKusuk.comment.domain.Comment;
import com.cona.KUsukKusuk.spot.domain.Spot;
import com.cona.KUsukKusuk.user.dto.BoomarkLikeResponseDto;
import com.cona.KUsukKusuk.user.dto.PageInfo;
import java.time.LocalDateTime;
import lombok.Builder;

@Builder
public record CommentListResponseDto(
String spotName,
Long spotId,
String usersComment,
String review,
LocalDateTime CommentcreateDate,

String author,


String spotImageurl,
long totalElements,
int page,
int size,
int totalPages
) {

public static CommentListResponseDto of (Comment comment, PageInfo pageInfo){
return CommentListResponseDto.builder()
.spotName(comment.getSpot().getSpotName())
.spotImageurl(comment.getSpot().getImageUrls().get(0))
.CommentcreateDate(comment.getCreatedDate())
.spotId(comment.getId())
.review(comment.getSpot().getReview())
.author(comment.getUser().getNickname())
.usersComment(comment.getComment())
.totalElements(pageInfo.getTotalElements())
.page(pageInfo.getPage())
.size(pageInfo.getSize())
.totalPages(pageInfo.getTotalPages())
.build();
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@

import com.cona.KUsukKusuk.comment.domain.Comment;
import com.cona.KUsukKusuk.user.domain.User;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CommentRepository extends JpaRepository<Comment, Long> {
void deleteAllByUser(User user);

List<Comment> findByUser(User user);

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.cona.KUsukKusuk.comment.domain.Comment;
import com.cona.KUsukKusuk.comment.dto.CommentGetResponse;
import com.cona.KUsukKusuk.comment.dto.CommentListResponseDto;
import com.cona.KUsukKusuk.comment.dto.CommentPaginationResponse;
import com.cona.KUsukKusuk.comment.exception.CommentNotFoundException;
import com.cona.KUsukKusuk.comment.exception.CommentUserNotMatchedException;
Expand All @@ -10,22 +11,29 @@
import com.cona.KUsukKusuk.spot.exception.SpotNotFoundException;
import com.cona.KUsukKusuk.spot.repository.SpotRepository;
import com.cona.KUsukKusuk.user.domain.User;
import com.cona.KUsukKusuk.user.dto.BoomarkLikeResponseDto;
import com.cona.KUsukKusuk.user.dto.PageInfo;
import com.cona.KUsukKusuk.user.service.UserService;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CommentService {
private final CommentRepository commentRepository;
private final SpotRepository spotRepository;
private final UserService userService;

public CommentService(CommentRepository commentRepository, SpotRepository spotRepository, UserService userService) {
this.commentRepository = commentRepository;
this.spotRepository = spotRepository;
this.userService = userService;
}

public Comment save(Comment comment) {
Comment savedComment = commentRepository.save(comment);
return savedComment;
Expand All @@ -37,13 +45,14 @@ public User getCurrentUser() {
return user;
}

public Spot getCurrentSpot(Long spotId) {
public Spot getCurrentSpot(Long spotId) {
Spot spot = spotRepository.findById(spotId)
.orElseThrow(() -> new SpotNotFoundException());
return spot;
}

public Comment getCurrentComment(String commentUserName , Spot spot, Long commentId) throws CommentNotFoundException, CommentUserNotMatchedException {
public Comment getCurrentComment(String commentUserName, Spot spot, Long commentId)
throws CommentNotFoundException, CommentUserNotMatchedException {
List<Comment> commentList = spot.getComments();
Comment wantToUpdate = null; // 초기화를 null로 설정
for (Comment comment : commentList) {
Expand All @@ -59,10 +68,11 @@ public Comment getCurrentComment(String commentUserName , Spot spot, Long commen
}

//commentUserName과 comment의 작성자 일치 확인
if (wantToUpdate.getUser().getUserId().equals(commentUserName))
if (wantToUpdate.getUser().getUserId().equals(commentUserName)) {
return wantToUpdate;
else
} else {
throw new CommentUserNotMatchedException("Don't have authority to update the comment.");
}

}

Expand All @@ -71,46 +81,54 @@ public void delete(Comment comment) {
}


public List<CommentGetResponse> getUserCommentsOfAllSpots(Long userId) {
//목표 : 사용자가 쓴 comment만 list<CommentGetResponse> 형태로 반환
List<Comment> comments = commentRepository.findAll();
List<CommentGetResponse> commentsByuser = new ArrayList<>();
Long cNum = 0L;
for (Comment c : comments)
{
if (c.getUser().getId().equals(userId))
commentsByuser.add(CommentGetResponse.of(++cNum,c,c.getCreatedDate()));
public List<CommentListResponseDto> getUserCommentsOfAllSpots(Long userId) {
// 사용자가 쓴 comment만 가져오기
User user = getCurrentUser();
List<Comment> comments = commentRepository.findByUser(user);
List<CommentListResponseDto> commentsByUser = new ArrayList<>();

// 가져온 comment를 CommentListResponseDto로 변환하여 리스트에 추가
for (Comment comment : comments) {
CommentListResponseDto commentDto = CommentListResponseDto.builder()
.spotName(comment.getSpot().getSpotName())
.spotId(comment.getSpot().getId())
.review(comment.getSpot().getReview())
.CommentcreateDate(comment.getSpot().getCreatedDate())
.author(comment.getUser().getNickname())
.spotImageurl(comment.getSpot().getImageUrls().get(0))
.build();
commentsByUser.add(commentDto);
}

return commentsByuser;

return commentsByUser;
}

public CommentPaginationResponse getPagedComments(List<CommentGetResponse> commentsByUser, Long pageNum, Long commentsInPage){
//commentsByuser 한 객체마다 pagination 해줘서 pagedComments 에 넣어주기
List<CommentPaginationResponse> pagedComments = new ArrayList<>();
public List<CommentListResponseDto> getPagedComments( int
pageNumber
, int pageSize) {

User user = getCurrentUser();
List<Comment> comments = commentRepository.findByUser(user);
System.out.println("comments.size() = " + comments.size());
List<CommentListResponseDto> pagedResponse = new ArrayList<>();

Long totalComments = (long) commentsByUser.size();
Long amountInBlock = commentsInPage;
Long lastPage = totalComments / amountInBlock; // 전체 페이지 수
// 나머지가 0보다 큰 경우에는 몫에 1을 더해주기
if (totalComments % amountInBlock > 0) {
lastPage++;
}
if (pageNum > lastPage || pageNum <= 0) {//요청하는 페이지가 존재하지 않는 경우
return null;
}

Long curPageNum = 1L;
int start = Math.min(pageNumber * pageSize, comments.size());
int end = Math.min((pageNumber + 1) * pageSize, comments.size());

for (int i = 0; i < totalComments; i += amountInBlock) {
int endIndex = (int) Math.min(i + amountInBlock, commentsByUser.size());
List<CommentGetResponse> currentPageComments = commentsByUser.subList(i, endIndex);
pagedComments.add(CommentPaginationResponse.of(currentPageComments, totalComments, curPageNum, lastPage, (long) (endIndex-i)));
curPageNum++;
if (start > end) {
start = end;
}
PageInfo pageInfo = new PageInfo();
pageInfo.setTotalElements(comments.size());
pageInfo.setPage(pageNumber + 1);
pageInfo.setSize(pageSize);
pageInfo.setTotalPages((int) Math.ceil((double) comments.size() / pageSize));

List<Comment> pagedcomments = comments.subList(start, end);

return pagedComments.get((int) (pageNum - 1));
return pagedcomments.stream()
.map(comment -> CommentListResponseDto.of(comment, pageInfo))
.collect(Collectors.toList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import java.time.LocalDateTime;
import java.time.ZoneId;
import lombok.Getter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
Expand All @@ -16,8 +17,9 @@ public abstract class BaseEntity {

@CreatedDate
@Column(updatable = false)
public LocalDateTime createdDate = LocalDateTime.now().plusHours(9);
public LocalDateTime createdDate = LocalDateTime.now(ZoneId.of("Asia/Seoul")); // 한국 시간으로 생성 날짜 설정

@LastModifiedDate
public LocalDateTime updatedDate = LocalDateTime.now().plusHours(9);
public LocalDateTime updatedDate = LocalDateTime.now(ZoneId.of("Asia/Seoul")); // 한국 시간으로 수정 날짜 설정
}

11 changes: 10 additions & 1 deletion src/main/java/com/cona/KUsukKusuk/global/s3/S3Service.java
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public List<String> updateImages(List<MultipartFile> files, String userId) throw


public void deleteSpotImages(Spot spot,User user) {
//현재 url에서 키 값을 추출해서 그대로 해당 키의 버킷 객체를
//현재 url에서 키 값을 추출해서 그대로 해당 키의 버킷 객체를 삭제(전부삭제)

List<String> imageUrls = spot.getImageUrls();
if(!imageUrls.isEmpty()){
Expand All @@ -141,5 +141,14 @@ public void deleteSpotImages(Spot spot,User user) {

}
}
public void deleteImagebyUrl(User member,String url) {



if (url != null) {
String key = extractString(url, member.getUserId());
amazonS3.deleteObject(bucket, key);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ public class CommentResponse {
private String author;
boolean deletable;
private LocalDateTime createdDate;
private String profileImage;

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.cona.KUsukKusuk.spot.dto;

import com.cona.KUsukKusuk.spot.domain.Spot;
import java.time.LocalDateTime;
import java.util.List;
import lombok.Builder;

Expand All @@ -14,6 +15,7 @@ public record SpotDetailResponse(Long spotId,
String author,
Boolean bookmark,
Boolean like,
LocalDateTime createDate,


String review) {
Expand All @@ -29,6 +31,7 @@ public static SpotDetailResponse fromSpot(Spot spot,Boolean isBookmark, Boolean
.review(spot.getReview())
.author(spot.getUser().getNickname())
.bookmark(isBookmark)
.createDate(spot.getCreatedDate())
.like(isLike)
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ public record SpotUpdateRequest (



String review
String review,

int deleteImageindex
){

}
17 changes: 15 additions & 2 deletions src/main/java/com/cona/KUsukKusuk/spot/service/SpotService.java
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,21 @@ public Spot updateSpot(Long spotId,List<MultipartFile> images, SpotUpdateRequest
if (!spot.getUser().equals(user)) {
throw new UserNotFoundException(HttpExceptionCode.USER_NOT_MATCH);
}
int deleteImageindex = spotUpdateRequest.deleteImageindex();


List<String> imageUrls = spot.getImageUrls();

if (deleteImageindex>=1 && deleteImageindex<=imageUrls.size()) {
String deleteimageurl = imageUrls.get(deleteImageindex-1);
imageUrls.remove(deleteImageindex-1);
//해당 인덱스에 대응하는 이미지 삭제후 다시 저장(영속).
spot.setImageUrls(imageUrls);
s3Service.deleteImagebyUrl(user,deleteimageurl);
}

if (!images.get(0).isEmpty()) {
//이미지가 존재할 경우
//이미지가 존재할 경우 기존 이미지 전부 삭제후 새로운 이미지 업로드
s3Service.deleteSpotImages(spot,user);
List<String> imagesurl = s3Service.uploadImages(images, username);
spot.setImageUrls(imagesurl);
Expand Down Expand Up @@ -182,7 +194,8 @@ private CommentResponse mapToCommentResponse(Comment comment, boolean currentUse
comment.getComment(),
comment.getUser().getNickname(),
deletable,
comment.getCreatedDate()
comment.getCreatedDate(),
comment.getUser().getProfileimage()
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ public String refreshToken(String encryptedRefreshToken) {
//redis에서 해당 키 검색해서 해당 토큰에 대응하는 key 추출
String userId = redisService.getValues(pureRefreshToken);

if (!redisService.checkExistsValue(userId)) {
throw new IncorrectRefreshTokenException();
}
User user = userRepository.findByUserId(userId)
.orElseThrow(UserNotFoundException::new);

Expand Down

0 comments on commit 12f1cfc

Please sign in to comment.