이제 특정 포스트를 조회하는 기능을 만들어 보자.
Endpoint는 GET /posts/{postsId} 로 postsId를 받아서 조회할 것이다.
//한개 조회
@ApiOperation(value = "게시글 상세조회기능")
@GetMapping("/{id}")
public Response<PostOneResponse> getPost(@PathVariable Long id){
return Response.success(postService.getPostById(id));
}
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Getter
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class PostOneResponse extends BaseEntity {
private Long id;
private String title;
private String body;
private String userName;
private LocalDateTime createdAt;
private LocalDateTime lastModifiedAt;
public static PostOneResponse fromEntity(Post post) {
return PostOneResponse.builder()
.id(post.getId())
.title(post.getTitle())
.body(post.getBody())
.userName(post.getUser().getUserName())
.createdAt(post.getCreatedAt())
.lastModifiedAt(post.getLastModifiedAt())
.build();
}
}
/**
*게시글 한개 조회
*/
public PostOneResponse getPostById(Long postsId) {
// PathVariable로 받은 id로 Post를 찾고 리턴한다.
Post post = postRepository.findById(postsId)
.orElseThrow(()-> new AppException(ErrorCode.POST_NOT_FOUND, postsId + "가 없습니다."));
return PostOneResponse.fromEntity(post);
}
public interface PostRepository extends JpaRepository<Post, Long> {
}
이제 상세조회를 할 수 있다.
Swagger를 통해 확인해 보자.

