포스트 상세조회

Sol's·2023년 1월 11일

프로젝트

목록 보기
11/16

이제 특정 포스트를 조회하는 기능을 만들어 보자.

Endpoint는 GET /posts/{postsId} 로 postsId를 받아서 조회할 것이다.

포스트 상세조회 기능

Controller

//한개 조회
    @ApiOperation(value = "게시글 상세조회기능")
    @GetMapping("/{id}")
    public Response<PostOneResponse> getPost(@PathVariable Long id){
        return Response.success(postService.getPostById(id));
    }

Dto

@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();
    }
}

Service

		/**
     *게시글 한개 조회
     */
    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);
    }

Repositoy

public interface PostRepository extends JpaRepository<Post, Long> {
}

이제 상세조회를 할 수 있다.
Swagger를 통해 확인해 보자.


profile
배우고, 생각하고, 행동해라

0개의 댓글