Skip to content

Commit

Permalink
Merge pull request #23 from pandahwang/comments
Browse files Browse the repository at this point in the history
Comments
  • Loading branch information
pandahwang authored Oct 2, 2024
2 parents 351032c + 9614dd3 commit 08d4609
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 108 deletions.
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
package com.TeamNull.LostArk.LostArk.controller;

import com.TeamNull.LostArk.LostArk.dto.CommentDto;
import com.TeamNull.LostArk.LostArk.entity.Comment;
import com.TeamNull.LostArk.LostArk.entity.User;
import com.TeamNull.LostArk.LostArk.repository.CommentRepository;
import com.TeamNull.LostArk.LostArk.repository.UserRepository;
import com.TeamNull.LostArk.LostArk.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

Expand All @@ -26,110 +19,39 @@
public class CommentController {

private final CommentService commentService;
private final CommentRepository commentRepository;
private final UserRepository userRepository;

@GetMapping("/{abc}") //abc라는 정수를 URL에서 추출합니다.
public Map<String, Object> commentList(
@PathVariable Integer abc, //추출한 정수를 저장할 변수 만듬
@PageableDefault(size = 5,sort = "createdAt", direction = Sort.Direction.DESC) //페이지의 규칙을 만듬
Pageable pageable //만든 규칙을 저장할 변수 생성
)
{

Pageable pageRequest = PageRequest.of(abc - 1, pageable.getPageSize(),pageable.getSort()); //추출된 정수와 규칙으로 페이지 변수를 만듬
Page<Comment> comments = commentRepository.findAll(pageRequest);
// commentRepository를 통해 추출된 데이터베이스의 자료를 만든 페이지에 적용 후 변수를 만듬

List<CommentDto.CommentResponseDto> responseDtoList = comments.getContent().stream()//데이터베이스에서 가져온 자료 중에서 각 페이지에 포함된 댓글 목록을 추출
//더 정확히는 댓글 content가 아닌 새로만들 댓글 목록이다.
.map(comment -> { // DTO를 통해 원하는 자료(댓글 목록의 자료)를 가진 리스트를 만듬
CommentDto.CommentResponseDto dto = new CommentDto.CommentResponseDto(
comment.getId(),
comment.getCreatedAt(),
comment.getContent(),
comment.getUser().getId(),
comment.getTopFactorResult(),
comment.getNickName()
);

return dto;
})
.toList();


int totalPages = comments.getTotalPages(); //데이터베이스 페이지에 있는 페이지를 이용해 규칙성 정수를 만듬
int currentPage = comments.getNumber() + 1;
int startPage = Math.max(1, currentPage - 2);
int endPage = Math.min(startPage + 4, totalPages);

// JSON 응답 구성
Map<String, Object> response = new HashMap<>(); //맵을 사용해 규칙성 정수와 원하는 자료를 가진 리스트를 추력함
response.put("comments", responseDtoList);
response.put("currentPage", currentPage);
response.put("startPage", startPage);
response.put("endPage", endPage);
response.put("totalPages", totalPages);

return response;

@GetMapping("/{abc}")
public Map<String, Object> commentAdd(@PathVariable Integer abc,
@PageableDefault(size = 5, sort = "createdAt", direction = Sort.Direction.ASC)
Pageable pageable) {
return commentService.getComments(abc, pageable);
}

}
@PostMapping("/{userId}")
public void addComment(@PathVariable UUID userId , @RequestBody CommentDto commentDto) {
//url로 부터 userId를 추출 하고, @RequestBody를 통해 추출한 body의 자료({}안의 자료)를 commentDto 변수에 적용
commentService.commentAdd(commentDto.getContent(),
commentDto.getPassword(),
commentDto.getNickname(),
userId
); //추출된 userId와 본문 데이터를 서비스 레이어로 전달합니다.
}
@PostMapping("/{userId}")
public void addComment(@PathVariable UUID userId, @RequestBody CommentDto commentDto)
{
commentService.creation(commentDto.getContent(),
commentDto.getPassword(),
commentDto.getNickname(),
userId
);
}

@DeleteMapping("/delete/{userId}/{commentId}")
public ResponseEntity<String> commentDelete(@PathVariable UUID userId,
@PathVariable Integer commentId,
@RequestBody Map<String, String> requestBody) {
String password = requestBody.get("password");

if (password == null || password.isEmpty()) {
return ResponseEntity.badRequest().body("비밀번호가 없습니다.");
}

return userRepository.findById(userId)
.map(user -> commentRepository.findById(commentId)
.filter(comment -> comment.getUser().getId().equals(userId))
.filter(comment -> comment.getPassword().equals(password))
.map(comment -> {
commentRepository.deleteById(commentId);
return ResponseEntity.ok("댓글이 성공적으로 삭제되었습니다");
})
.orElse(ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("해당 사용자가 작성한 댓글을 찾을 수 없습니다"))
)
.orElse(ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("해당 사용자를 찾을 수 없습니다."));
@RequestBody CommentDto dropComment)
{
return commentService.removal(userId,commentId,dropComment.getPassword());
}

@PutMapping("/update/{userId}/{commentId}")
public ResponseEntity<String> commentUpdate(@PathVariable UUID userId,
@PathVariable int commentId,
@RequestBody CommentDto updatedComment) {
if (updatedComment == null || updatedComment.getPassword() == null) {
return ResponseEntity.badRequest().body("요청 본문 또는 비밀번호가 없습니다.");
}

return userRepository.findById(userId)
.flatMap(user -> commentRepository.findById(commentId)
.filter(comment -> comment.getUser().getId().equals(userId)) // 해당 유저의 댓글인지 확인
.filter(comment -> comment.getPassword().equals(updatedComment.getPassword())) // 비밀번호 확인
.map(comment -> {
comment.setContent(updatedComment.getContent()); // 댓글 내용 업데이트
commentRepository.save(comment); // 변경된 댓글 저장
return ResponseEntity.ok("댓글이 성공적으로 업데이트되었습니다.");
})
)
.orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("해당 사용자가 작성한 댓글을 찾을 수 없습니다."));
@PathVariable int commentId,
@RequestBody CommentDto updatedComment)
{
return commentService.edition(userId,commentId,updatedComment.getPassword(),updatedComment.getContent());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@


import com.TeamNull.LostArk.LostArk.entity.Comment;
import com.TeamNull.LostArk.LostArk.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;
import java.util.UUID;

public interface CommentRepository extends JpaRepository<Comment,Integer> {
Page<Comment> findAll(Pageable pageable); //데이터베이스를 페이지화하고, JPA를 통해 데이터베이스의 자료 추출
Optional<Comment> findByUserIdAndId(UUID userId, int id);
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
package com.TeamNull.LostArk.LostArk.service;


import com.TeamNull.LostArk.LostArk.dto.CommentDto;
import com.TeamNull.LostArk.LostArk.entity.Comment;
import com.TeamNull.LostArk.LostArk.entity.User;
import com.TeamNull.LostArk.LostArk.repository.CommentRepository;
import com.TeamNull.LostArk.LostArk.repository.ResultRepository;
import com.TeamNull.LostArk.LostArk.repository.UserRepository;
import lombok.RequiredArgsConstructor;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;



import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
Expand All @@ -22,9 +32,36 @@ public class CommentService {
private final ResultRepository resultRepository;
private final UserRepository userRepository;

public Map<String, Object> getComments(int page, Pageable pageable) {
Pageable pageRequest = PageRequest.of(page - 1, pageable.getPageSize(), pageable.getSort());
Page<Comment> comments = commentRepository.findAll(pageRequest);

List<CommentDto.CommentResponseDto> responseDtoList = comments.getContent().stream()
.map(comment -> new CommentDto.CommentResponseDto(
comment.getId(),
comment.getCreatedAt(),
comment.getPassword(),
comment.getUser().getId(),
comment.getTopFactorResult(),
comment.getNickName()
)).toList();

int totalPage = comments.getTotalPages();
int currentPage = comments.getNumber() + 1;
int startPage = Math.max(1, currentPage - 2);
int endPage = Math.min(totalPage, startPage + 4);

Map<String, Object> response = new HashMap<>();
response.put("comments", responseDtoList);
response.put("TOTALPAGE", totalPage);
response.put("CURRENTPAGE", currentPage);
response.put("STARTPAGE", startPage);
response.put("ENDPAGE", endPage);

return response;
}


public void commentAdd( String content,
public void creation( String content,
String password,
String nickname,
UUID userId
Expand All @@ -35,24 +72,51 @@ public void commentAdd( String content,
comment.setPassword(password);
comment.setContent(content);
comment.setNickName(nickname);


String topFactorResult = resultRepository.findByUserId(userId)//resultRepository를 통해 userId를 찾아 userId가 포함된 모든 인스턴스(행)을 자져옴.
.map(result -> result.getTopFactor1().getJobName())//가져온 인스턴스에서 getJobName 속성의 String 자료만 추출함
.orElseThrow(()-> new IllegalArgumentException("없습니다" + userId));

comment.setTopFactorResult(topFactorResult);

User user = userRepository.findById(userId)// url로 부터 추출한 userId를 userRepository를 통해 찾아 Comment의 User user 변수에 저장
.orElseThrow(()-> new IllegalArgumentException("없습니다."));


comment.setUser(user); //그리고 set을 통해 데이터베이스의 데이터를 추가


commentRepository.save(comment);//설정이 완료된 Comment 객체를 데이터베이스에 저장합니다.
}

public ResponseEntity<String> removal(UUID userId,
Integer commentId,
String password){
if (password == null || password.isEmpty()) {
return ResponseEntity.badRequest().body("비밀번호가 없습니다.");
}

return commentRepository.findByUserIdAndId(userId, commentId)
.filter(comment -> comment.getPassword().equals(password))
.map(comment -> {
commentRepository.deleteById(commentId);
return ResponseEntity.ok("댓글이 성공적으로 삭제되었습니다");
}).orElseGet(()->
ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("해당 사용자가 작성한 댓글을 찾을 수 없습니다."));
}


public ResponseEntity<String> edition(UUID userId, Integer commentId, String password, String Content)
{
if (password == null || password.isEmpty()) {
return ResponseEntity.badRequest().body("요청 본문 또는 비밀번호가 없습니다.");
}
return commentRepository.findByUserIdAndId(userId, commentId)
.filter(comment -> comment.getPassword().equals(password))
.map(comment -> {
comment.setContent(Content);
commentRepository.save(comment);
return ResponseEntity.ok("댓글이 성공적으로 수정되었습니다.");

}).orElseGet(()-> ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("해당 사용자가 작성한 댓글을 찾을 수 없습니다."));
}
}

0 comments on commit 08d4609

Please sign in to comment.