Skip to content

Commit

Permalink
Merge pull request #43 from 9oormthon-univ/dev
Browse files Browse the repository at this point in the history
⚡Feat: 댓글 & 게시글 이미지 관련 로직 수정
  • Loading branch information
eunxeum authored Nov 23, 2024
2 parents 08729fe + 0c0f02a commit 17eda10
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import univ.yesummit.domain.board.api.dto.request.BoardSaveReqDto;
import univ.yesummit.domain.board.api.dto.request.BoardUpdateReqDto;
import univ.yesummit.domain.board.api.dto.response.BoardInfoResDto;
import univ.yesummit.domain.board.application.BoardService;
import univ.yesummit.domain.board.domain.Board;
import univ.yesummit.domain.board.domain.BoardPicture;
import univ.yesummit.global.resolver.LoginUser;
import univ.yesummit.global.resolver.User;

Expand All @@ -23,7 +23,6 @@
@RestController
@RequestMapping("/v1/api/board")
public class BoardController {

private final BoardService boardService;
public BoardController(BoardService boardService) {
this.boardService = boardService;
Expand All @@ -34,8 +33,9 @@ public BoardController(BoardService boardService) {
@ApiResponse(responseCode = "200", description = "등록 성공"),
@ApiResponse(responseCode = "401", description = "인증실패", content = @Content(schema = @Schema(example = "INVALID_HEADER or INVALID_TOKEN"))),
})
@PostMapping(value= "/summit/{summitId}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@PostMapping("/summit/{summitId}")
public ResponseEntity<String> boardSave(@User LoginUser loginUser,
@PathVariable Long summitId,
@RequestBody BoardSaveReqDto boardSaveReqDto) {
Long boardId = boardService.boardSave(loginUser.getMemberId(), boardSaveReqDto);
String message = String.format("%d번 게시글 등록!", boardId);
Expand All @@ -49,8 +49,8 @@ public ResponseEntity<String> boardSave(@User LoginUser loginUser,
@ApiResponse(responseCode = "404", description = "게시글 없음", content = @Content(schema = @Schema(example = "게시글이 존재하지 않습니다."))),
})
@GetMapping("/summit/{summitId}/list")
public ResponseEntity<List<BoardInfoResDto>> allBoardInfo(@PathVariable Long summitId) {
List<BoardInfoResDto> allBoards = boardService.allBoardInfoBySummitId(summitId);
public ResponseEntity<List<BoardInfoResDto>> allBoardInfo(@PathVariable Long summitId, @User LoginUser loginUser) {
List<BoardInfoResDto> allBoards = boardService.allBoardInfoBySummitId(summitId, loginUser.getMemberId());
return new ResponseEntity<>(allBoards, HttpStatus.OK);
}

Expand Down Expand Up @@ -106,5 +106,4 @@ public ResponseEntity<Void> boardDelete(@User LoginUser loginUser,
boardService.boardDelete(loginUser.getMemberId(), boardId);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,19 @@

import java.util.List;

import java.util.ArrayList;
public record BoardSaveReqDto(
String title,
String content,
List<String> imageUrl,
String serviceUrl,
String PTUrl
) {
public BoardSaveReqDto {
if (imageUrl == null) {
throw new IllegalArgumentException("이미지 URL null");
}
}
public Board toEntity(Member member) {
List<BoardPicture> boardPictures = imageUrl.stream()
List<String> images = (imageUrl == null) ? new ArrayList<>() : imageUrl;

// imageUrl 리스트를 이용해 BoardPicture 객체 리스트 생성
List<BoardPicture> boardPictures = images.stream()
.map(url -> BoardPicture.builder()
.imageUrl(url)
.build())
Expand All @@ -29,10 +28,9 @@ public Board toEntity(Member member) {
.title(title)
.content(content)
.pictures(boardPictures)
.writer(member)
.serviceUrl(serviceUrl)
.PTUrl(PTUrl)
.writer(member)
.build();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import univ.yesummit.domain.board.api.dto.request.BoardSaveReqDto;
import univ.yesummit.domain.board.api.dto.request.BoardUpdateReqDto;
import univ.yesummit.domain.board.api.dto.response.BoardInfoResDto;
Expand All @@ -12,9 +13,13 @@
import univ.yesummit.domain.board.domain.repository.BoardLikeRepository;
import univ.yesummit.domain.board.domain.repository.BoardPictureRepository;
import univ.yesummit.domain.board.domain.repository.BoardRepository;
import univ.yesummit.domain.feed.entity.Feed;
import univ.yesummit.domain.feed.repository.FeedRepository;
import univ.yesummit.domain.member.entity.Member;
import univ.yesummit.domain.member.repository.MemberRepository;
import univ.yesummit.global.s3.service.S3Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

Expand All @@ -28,44 +33,51 @@ public class BoardService {
private final BoardPictureRepository boardPictureRepository;
private final BoardLikeRepository boardLikeRepository;
private final MemberRepository memberRepository;
private final FeedRepository feedRepository;

// 게시글 저장
@Transactional
public Long boardSave(Long memberId, BoardSaveReqDto boardSaveReqDto) {
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new IllegalArgumentException("회원이 존재하지 않습니다." + memberId));
.orElseThrow(() -> new IllegalArgumentException("회원이 존재하지 않습니다. " + memberId));

Board board = boardSaveReqDto.toEntity(member);

if (board == null) {
throw new IllegalStateException("게시글 객체 생성 실패.");
}
List<Feed> feeds = getFeedsByMember(member);
boardImageSave(board, boardSaveReqDto.imageUrl(), feeds);

boardImageSave(board, boardSaveReqDto);
Board savedBoard = boardRepository.save(board);

if (savedBoard == null) {
throw new IllegalStateException("게시글 저장에 실패했습니다.");
}

return savedBoard.getBoardId();
}

private void boardImageSave(Board board, BoardSaveReqDto boardSaveReqDto) {
for (String imageUrl : boardSaveReqDto.imageUrl()) {
// Feed 데이터를 가져오는 헬퍼 메서드
private List<Feed> getFeedsByMember(Member member) {
return feedRepository.findAllByMember(member);
}


private void boardImageSave(Board board, List<String> imageUrls, List<Feed> feeds) {
for (String imageUrl : imageUrls) {
boardPictureRepository.save(BoardPicture.builder()
.board(board)
.imageUrl(imageUrl) // URL 직접 저장
.build());
}
for (Feed feed : feeds) {
boardPictureRepository.save(BoardPicture.builder()
.board(board)
.imageUrl(imageUrl)
.feed(feed) // Feed에서 이미지 추출하여 저장
.build());
}
}

// 주제별 게시글 전체 조회

@Transactional
public List<BoardInfoResDto> allBoardInfoBySummitId(Long summitId) {
public List<BoardInfoResDto> allBoardInfoBySummitId(Long summitId, Long memberId) {
List<Board> boards = boardRepository.findBySummitId(summitId);
Member member = memberId != null ? memberRepository.findById(memberId).orElse(null) : null; // memberId로 member 조회
return boards.stream()
.map(board -> BoardInfoResDto.of(null, board, false))
.map(board -> BoardInfoResDto.of(member, board, false)) // member 정보를 전달
.collect(Collectors.toList());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class BoardPicture {

@Builder
private BoardPicture(String imageUrl, Board board, Feed feed) {
this.imageUrl = imageUrl;
this.imageUrl = (feed != null) ? feed.getImage() : imageUrl;
this.board = board;
this.feed = feed;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
import org.springframework.data.jpa.repository.JpaRepository;
import univ.yesummit.domain.board.domain.Board;
import univ.yesummit.domain.board.domain.BoardPicture;
import univ.yesummit.domain.feed.entity.Feed;

import java.util.List;

public interface BoardPictureRepository extends JpaRepository<BoardPicture, String> {

List<BoardPicture> findByFeed(Feed feed);
void deleteByBoardBoardId(Long boardId);
void deleteByBoardAndImageUrlIn(Board board, List<String> urlsToDelete);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import univ.yesummit.domain.comment.api.dto.request.CommentSaveReqDto;
import univ.yesummit.domain.comment.api.dto.request.CommentUpdateReqDto;
import univ.yesummit.domain.comment.application.CommentService;
import univ.yesummit.global.resolver.LoginUser;
import univ.yesummit.global.resolver.User;

@RestController
@RequiredArgsConstructor
Expand All @@ -23,11 +25,11 @@ public class CommentController {
@Operation(summary = "댓글 등록", description = "댓글을 등록합니다.")
@ApiResponse(responseCode = "200", description = "댓글 등록 성공")
@ApiResponse(responseCode = "401", description = "인증 실패", content = @Content(schema = @Schema(example = "INVALID_HEADER or INVALID_TOKEN")))
@PostMapping("/")
public ResponseEntity<String> commentSave(@AuthenticationPrincipal String email,
@PostMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> commentSave(@User LoginUser loginUser,
@RequestBody CommentSaveReqDto commentSaveReqDto) {

commentService.commentSave(email, commentSaveReqDto);
commentService.commentSave(loginUser.getMemberId(), commentSaveReqDto);

String responseMessage = String.format("%d 게시글에 댓글이 등록되었습니다.", commentSaveReqDto.boardId());
return ResponseEntity.status(HttpStatus.CREATED).body(responseMessage);
Expand All @@ -36,12 +38,12 @@ public ResponseEntity<String> commentSave(@AuthenticationPrincipal String email,
@Operation(summary = "댓글 수정", description = "댓글을 수정합니다.")
@ApiResponse(responseCode = "200", description = "댓글 수정 성공")
@ApiResponse(responseCode = "401", description = "인증 실패", content = @Content(schema = @Schema(example = "INVALID_HEADER or INVALID_TOKEN")))
@PutMapping("/{commentId}")
public ResponseEntity<String> commentUpdate(@AuthenticationPrincipal String email,
@PutMapping(value = "/{commentId}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> commentUpdate(@User LoginUser loginUser,
@PathVariable("commentId") Long commentId,
@RequestBody CommentUpdateReqDto commentUpdateReqDto) {

commentService.commentUpdate(email, commentId, commentUpdateReqDto);
commentService.commentUpdate(loginUser.getMemberId(), commentId, commentUpdateReqDto);

String responseMessage = String.format("%d 게시글의 댓글이 수정돠었습니다.", commentId);
return ResponseEntity.status(HttpStatus.OK).body(responseMessage);
Expand All @@ -50,10 +52,10 @@ public ResponseEntity<String> commentUpdate(@AuthenticationPrincipal String emai
@Operation(summary = "댓글 삭제", description = "댓글을 삭제합니다.")
@ApiResponse(responseCode = "200", description = "댓글 삭제 성공")
@ApiResponse(responseCode = "401", description = "인증 실패", content = @Content(schema = @Schema(example = "INVALID_HEADER or INVALID_TOKEN")))
@DeleteMapping("/{commentId}")
public ResponseEntity<String> commentDelete(@AuthenticationPrincipal String email,
@DeleteMapping(value = "/{commentId}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> commentDelete(@User LoginUser loginUser,
@PathVariable("commentId") Long commentId) {
commentService.commentDelete(email, commentId);
commentService.commentDelete(loginUser.getMemberId(), commentId);

String responseMessage = String.format("%d 게시글의 댓글이 삭제되었습니다.", commentId);
return ResponseEntity.status(HttpStatus.OK).body(responseMessage);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public class CommentService {

// 댓글 저장
@Transactional
public void commentSave(String email, CommentSaveReqDto commentSaveReqDto) {
Member member = memberRepository.findByEmail(email)
public void commentSave(Long id, CommentSaveReqDto commentSaveReqDto) {
Member member = memberRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("회원이 존재하지 않습니다."));

Board board = boardRepository.findById(commentSaveReqDto.boardId())
Expand All @@ -36,8 +36,8 @@ public void commentSave(String email, CommentSaveReqDto commentSaveReqDto) {

// 댓글 수정
@Transactional
public CommentInfoResDto commentUpdate(String email, Long commentId, CommentUpdateReqDto commentUpdateReqDto){
Member member = memberRepository.findByEmail(email)
public CommentInfoResDto commentUpdate(Long id, Long commentId, CommentUpdateReqDto commentUpdateReqDto){
Member member = memberRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("회원이 존재하지 않습니다."));

Comment comment = commentRepository.findById(commentId)
Expand All @@ -52,8 +52,8 @@ public CommentInfoResDto commentUpdate(String email, Long commentId, CommentUpda

// 댓글 삭제
@Transactional
public void commentDelete(String email, Long commentId) {
Member member = memberRepository.findByEmail(email)
public void commentDelete(Long id, Long commentId) {
Member member = memberRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("회원이 존재하지 않습니다."));

Comment comment = commentRepository.findById(commentId)
Expand Down

0 comments on commit 17eda10

Please sign in to comment.