반응형
게시글 CRUD 구현
Controller
package com.burrow.burrow.post.controller;
import com.burrow.burrow.post.dto.CommonResponseDto;
import com.burrow.burrow.post.dto.PostRequestDto;
import com.burrow.burrow.post.dto.PostResponseDto;
import com.burrow.burrow.post.service.PostService;
import com.burrow.burrow.user.security.UserDetailsImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.RejectedExecutionException;
@RequestMapping("/api/posts")
@RestController
@RequiredArgsConstructor
public class PostController {
private final PostService postService;
//게시글 생성
@PostMapping
public ResponseEntity<?> createPosts(
@RequestBody PostRequestDto postRequestDto,
@AuthenticationPrincipal UserDetailsImpl userDetails) {
try {
PostResponseDto postResponseDto = postService.createPosts(postRequestDto, userDetails);
return ResponseEntity.ok().body(postResponseDto);
} catch (RejectedExecutionException | IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(new CommonResponseDto(ex.getMessage(), HttpStatus.BAD_REQUEST.value()));
}
}
//전체 게시글 조회
@GetMapping("/list")
public List<PostResponseDto> getAllPosts() {
return postService.getAllPosts();
}
//단건 게시글 조회
@GetMapping("/{postId}")
public ResponseEntity<CommonResponseDto> getPost(@PathVariable Long postId) {
try {
PostResponseDto postResponseDto = postService.getPostDto(postId);
return ResponseEntity.ok().body(postResponseDto);
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().body(new CommonResponseDto(e.getMessage(), HttpStatus.BAD_REQUEST.value()));
}
}
//게시글 수정
@PatchMapping("/{postId}")
public ResponseEntity<CommonResponseDto> updatePost(
@PathVariable Long postId,
@RequestBody PostRequestDto postRequestDto,
@AuthenticationPrincipal UserDetailsImpl userDetails
) {
try {
PostResponseDto postResponseDto = postService.updatePost(postId, postRequestDto, userDetails);
return ResponseEntity.ok().body(postResponseDto);
} catch (RejectedExecutionException | IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(new CommonResponseDto(ex.getMessage(), HttpStatus.BAD_REQUEST.value()));
}
}
//게시글 삭제
@DeleteMapping("/{postId}")
public ResponseEntity<CommonResponseDto> deletePost(
@PathVariable Long postId,
@AuthenticationPrincipal UserDetailsImpl userDetails
) {
try {
postService.deletePost(postId, userDetails);
return ResponseEntity.ok().body(new CommonResponseDto("정상적으로 삭제 되었습니다.", HttpStatus.OK.value()));
} catch (RejectedExecutionException | IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(new CommonResponseDto(ex.getMessage(), HttpStatus.BAD_REQUEST.value()));
}
}
}
Service
package com.burrow.burrow.post.service;
import com.burrow.burrow.comment.entity.Comment;
import com.burrow.burrow.comment.repository.CommentRepository;
import com.burrow.burrow.post.dto.PostRequestDto;
import com.burrow.burrow.post.dto.PostResponseDto;
import com.burrow.burrow.post.entity.Post;
import com.burrow.burrow.post.repository.PostRepository;
import com.burrow.burrow.user.entity.User;
import com.burrow.burrow.user.security.UserDetailsImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RejectedExecutionException;
@Service
@RequiredArgsConstructor
public class PostService {
private final PostRepository postRepository;
private final CommentRepository commentRepository;
//게시물 저장 역할
public PostResponseDto createPosts(PostRequestDto postRequestDto, UserDetailsImpl userDetails) {
// 제목(title)과 내용(content)이 비어 있는 경우
if (postRequestDto.getTitle() == null || postRequestDto.getTitle().trim().isEmpty()) {
// 제목이 비어있을 때의 에러 메시지 처리
throw new IllegalArgumentException("제목이 비어있습니다. 제목을 작성해 주세요.");
} else if (postRequestDto.getContent() == null || postRequestDto.getContent().trim().isEmpty()) {
// 내용이 비어있을 때의 에러 메시지 처리
throw new IllegalArgumentException("내용이 비어있습니다. 내용을 작성해 주세요.");
}
//받아온 정보 객체에 저장
Post post = new Post(postRequestDto, userDetails);
//DB에 저장
Post savePost = postRepository.save(post);
//DB에 저장된 값 반환
return new PostResponseDto(savePost);
}
//게시글 전제 조회
public List<PostResponseDto> getAllPosts() {
List<Post> postList = postRepository.findAll();
List<PostResponseDto> responseDtoList = new ArrayList<>();
for (Post post : postList) {
responseDtoList.add(new PostResponseDto(post));
}
return responseDtoList;
}
//게시글 단건 조회
public PostResponseDto getPostDto(Long postId) {
Post post = getPost(postId);
List<Comment> commentList = commentRepository.findAllByPostId(postId);
return new PostResponseDto(post, commentList, post.getUser().getNickname());
}
//게시글 수정
@Transactional
public PostResponseDto updatePost(Long postId, PostRequestDto postRequestDto, UserDetailsImpl userDetails) {
// 제목(title)과 내용(content)이 비어 있는 경우
if (postRequestDto.getTitle() == null || postRequestDto.getTitle().trim().isEmpty()) {
// 제목이 비어있을 때의 에러 메시지 처리
throw new IllegalArgumentException("제목이 비어있습니다. 제목을 작성해 주세요.");
} else if (postRequestDto.getContent() == null || postRequestDto.getContent().trim().isEmpty()) {
// 내용이 비어있을 때의 에러 메시지 처리
throw new IllegalArgumentException("내용이 비어있습니다. 내용을 작성해 주세요.");
}
Post post = getUserPost(postId, userDetails.getUser());
post.setTitle(postRequestDto.getTitle());
post.setContent(postRequestDto.getContent());
post.setModifiedAt(post.getModifiedAt());
return new PostResponseDto(post);
}
//게시글 삭제
@Transactional
public void deletePost(Long postId, UserDetailsImpl userDetails
) {
Post post = getUserPost(postId, userDetails.getUser());
postRepository.delete(post);
}
//게시글 예외처리
private Post getPost(Long postId) {
return postRepository.findById(postId)
.orElseThrow(() -> new IllegalArgumentException("게시글이 존재하지 않습니다."));
}
//게시글 수정시 예외처리
public Post getUserPost(Long postId, User user) {
Post post = getPost(postId);
if (!user.getUid().equals(post.getUser().getUid())) {
throw new RejectedExecutionException("수정 권한이 없습니다.");
}
return post;
}
}
Entity
package com.burrow.burrow.post.entity;
import com.burrow.burrow.post.dto.PostRequestDto;
import com.burrow.burrow.user.entity.User;
import com.burrow.burrow.user.security.UserDetailsImpl;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import java.io.Serializable;
import java.time.LocalDateTime;
@Getter
@Entity(name = "Posts")
@NoArgsConstructor
public class Post implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "title", nullable = false)
private String title;
@Column(name = "content", nullable = false)
private String content;
@CreatedDate
@Column(name = "created_at", updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private LocalDateTime createdAt;
@LastModifiedDate
@Column(name = "modified_at")
@Temporal(TemporalType.TIMESTAMP)
private LocalDateTime modifiedAt;
@ManyToOne
@JoinColumn(name = "users_id")
private User user;
public Post(PostRequestDto postRequestDto, UserDetailsImpl userDetails) {
this.title = postRequestDto.getTitle();
this.content = postRequestDto.getContent();
this.createdAt = LocalDateTime.now();
this.modifiedAt = LocalDateTime.now();
this.user = userDetails.getUser();
}
public void setUser(User user) {
this.user = user;
}
public void setTitle(String title) {
this.title = title;
}
public void setContent(String content) {
this.content = content;
}
public void setModifiedAt(LocalDateTime modifiedAt) {
this.modifiedAt = LocalDateTime.now();
}
}
Dto
package com.burrow.burrow.post.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CommonResponseDto {
private String msg;
private Integer status;
}
package com.burrow.burrow.post.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
@Getter
public class PostRequestDto {
@NotBlank
private String title;
@NotBlank
private String content;
}
package com.burrow.burrow.post.dto;
import com.burrow.burrow.comment.dto.CommentResponse;
import com.burrow.burrow.comment.entity.Comment;
import com.burrow.burrow.post.entity.Post;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Getter
@NoArgsConstructor
public class PostResponseDto extends CommonResponseDto {
private Long id;
private String title;
private String content;
private LocalDateTime createdAt;
private LocalDateTime modifiedAt;
private List<CommentResponse> commentList;
private String nickname;
public PostResponseDto(Post post) {
this.id = post.getId();
this.title = post.getTitle();
this.content = post.getContent();
this.createdAt = post.getCreatedAt();
this.modifiedAt = post.getModifiedAt();
this.nickname = post.getUser().getNickname();
}
public PostResponseDto(Post post, List<Comment> commentList, String nickname) {
this.title = post.getTitle();
this.content = post.getContent();
this.createdAt = post.getCreatedAt();
this.modifiedAt = post.getModifiedAt();
this.commentList = new ArrayList<>();
for (Comment comment : commentList) {
this.commentList.add(new CommentResponse(comment));
}
this.nickname = nickname;
}
}
package com.burrow.burrow.post.dto;
import com.burrow.burrow.user.entity.User;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class UserDto {
private String username;
public UserDto(User user) {
this.username = user.getUid();
}
}
Repository
package com.burrow.burrow.post.repository;
import com.burrow.burrow.post.entity.Post;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PostRepository extends JpaRepository<Post, Long> {
}
반응형
'내배캠_Spring _3기 > 프로젝트' 카테고리의 다른 글
[프로젝트] Trello 협업 툴 만들기 - 1 (0) | 2023.12.26 |
---|---|
[프로젝트] Burrow 익명사이트 만들기 - 5 (0) | 2023.12.11 |
[프로젝트] Burrow 익명사이트 만들기 - 3 (0) | 2023.12.07 |
[프로젝트] Burrow 익명사이트 만들기 - 2 (0) | 2023.12.06 |
[프로젝트] Burrow 익명사이트 만들기 - 1 (1) | 2023.12.05 |