Skip to content

Commit

Permalink
Merge pull request #78 from KNU-HAEDAL-Website/feat-get-activity-post…
Browse files Browse the repository at this point in the history
…-issue-75

Feat: 게시글 조회 API
  • Loading branch information
tfer2442 authored Aug 15, 2024
2 parents a363af4 + 3385168 commit b358508
Show file tree
Hide file tree
Showing 10 changed files with 277 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
.requestMatchers(HttpMethod.DELETE, "/activities/{activityId}/boards/{boardId}").hasAnyRole("WEB_MASTER", "ADMIN", "TEAM_LEADER")
.requestMatchers(HttpMethod.PATCH, "/activities/{activityId}/boards/{boardId}/**").hasAnyRole("WEB_MASTER", "ADMIN", "TEAM_LEADER")
.requestMatchers("/private/users").authenticated()
.requestMatchers("/activities/{activityId}/boards","/activities/{activityId}/boards/{boardId}","/login", "/", "/join/**", "/reissue", "/swagger-ui/**", "/v3/api-docs/**", "/users/**","/semesters/**").permitAll()
.requestMatchers("/posts/slider", "/posts/{postId}","/boards/{boardId}/posts", "/posts","/activities/{activityId}/boards","/activities/{activityId}/boards/{boardId}","/login", "/", "/join/**", "/reissue", "/swagger-ui/**", "/v3/api-docs/**", "/users/**","/semesters/**").permitAll()
.anyRequest().authenticated());

//JWTFilter 등록
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
Expand Down
67 changes: 62 additions & 5 deletions src/main/java/com/haedal/haedalweb/controller/PostController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import com.haedal.haedalweb.constants.ErrorCode;
import com.haedal.haedalweb.constants.SuccessCode;
import com.haedal.haedalweb.dto.request.CreatePostDTO;
import com.haedal.haedalweb.dto.response.PostDTO;
import com.haedal.haedalweb.dto.response.PostSliderDTO;
import com.haedal.haedalweb.dto.response.PostSummaryDTO;
import com.haedal.haedalweb.dto.response.PreSignedUrlDTO;
import com.haedal.haedalweb.dto.response.common.SuccessResponse;
import com.haedal.haedalweb.service.PostService;
Expand All @@ -16,12 +19,16 @@
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;

Expand Down Expand Up @@ -88,9 +95,59 @@ public ResponseEntity<SuccessResponse> deleteNoticePost(@PathVariable Long postI
return ResponseUtil.buildSuccessResponseEntity(SuccessCode.DELETE_POST_SUCCESS);
}

// @Operation(summary = "활동 게시글 목록 조회")
// @GetMapping("/boards/{boardId}/posts")
// public ResponseEntity<?> getActivityPosts(@PathVariable Long boardId) {
//
// }
@Operation(summary = "활동 게시글 목록 조회")
@ApiErrorCodeExamples({ErrorCode.NOT_FOUND_BOARD_ID, ErrorCode.NOT_FOUND_POST_ID})
@Parameters({
@Parameter(name = "boardId", description = "게시글 조회할 게시판 ID"),
@Parameter(name = "page", description = "조회 할 page, default: 0"),
@Parameter(name = "size", description = "한 번에 조회 할 page 수, default: 10")
})
@GetMapping("/boards/{boardId}/posts")
public ResponseEntity<Page<PostSummaryDTO>> getActivityPosts(@PathVariable Long boardId,
@RequestParam(name = "page", defaultValue = "0") Integer page,
@RequestParam(name = "size", defaultValue = "10") Integer size) {
Page<PostSummaryDTO> posts = postService.getPosts(boardId, PageRequest.of(page, size, Sort.by(Sort.Order.asc("id"))));

return ResponseEntity.ok(posts);
}

@Operation(summary = "공지사항, 이벤트 게시글 목록 조회")
@ApiErrorCodeExamples({ErrorCode.NOT_FOUND_POST_TYPE, ErrorCode.NOT_FOUND_POST_ID})
@Parameters({
@Parameter(name = "page", description = "조회 할 page, default: 0"),
@Parameter(name = "size", description = "한 번에 조회 할 page 수, default: 10")
})
@GetMapping("/posts")
public ResponseEntity<Page<PostSummaryDTO>> getActivityPosts(@RequestParam(name = "postType") String postType,
@RequestParam(name = "page", defaultValue = "0") Integer page,
@RequestParam(name = "size", defaultValue = "10") Integer size) {
Page<PostSummaryDTO> posts = postService.getPosts(postType, PageRequest.of(page, size, Sort.by(Sort.Order.asc("id"))));

return ResponseEntity.ok(posts);
}

@Operation(summary = "게시글 단일 조회")
@ApiErrorCodeExamples({ErrorCode.NOT_FOUND_POST_ID})
@Parameters({
@Parameter(name = "postId", description = "해당 게시글 ID")
})
@GetMapping("/posts/{postId}")
public ResponseEntity<PostDTO> getPost(@PathVariable Long postId) {
PostDTO post = postService.getPost(postId);

return ResponseEntity.ok(post);
}

@Operation(summary = "이벤트 게시글 슬라이더 조회")
@Parameters({
@Parameter(name = "page", description = "조회 할 page, default: 0"),
@Parameter(name = "size", description = "한 번에 조회 할 page 수, default: 10")
})
@GetMapping("/posts/slider")
public ResponseEntity<Page<PostSliderDTO>> getSliderPosts(@RequestParam(name = "page", defaultValue = "0") Integer page,
@RequestParam(name = "size", defaultValue = "5") Integer size) {
Page<PostSliderDTO> posts = postService.getSliderPosts(PageRequest.of(page, size, Sort.by(Sort.Order.desc("id"))));

return ResponseEntity.ok(posts);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class CreateBoardDTO {
@Schema(description = "게시판 이름", example = "게시판1")
@Pattern(regexp = "^[가-힣a-zA-Z0-9]*$", message = "영어, 숫자, 한글만 입력가능합니다.")
@Pattern(regexp = "^[가-힣a-zA-Z0-9\\s]*$", message = "영어, 숫자, 한글만 입력가능합니다.")
@Size(min = 1, max = 15, message = "게시판 이름은 1자 이상 15자 이하여야 합니다.")
private String boardName;

Expand Down
13 changes: 10 additions & 3 deletions src/main/java/com/haedal/haedalweb/dto/response/PostDTO.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package com.haedal.haedalweb.dto.response;

import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;

import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
Expand All @@ -10,6 +13,7 @@
import lombok.NoArgsConstructor;


@JsonInclude(JsonInclude.Include.NON_NULL)
@Getter
@AllArgsConstructor
@Builder
Expand All @@ -25,13 +29,16 @@ public class PostDTO {
private String postContent;

@Schema(description = "게시글 대표 이미지 파일 Url")
private String postImageUrl;
private URL postImageUrl;

@Schema(description = "게시글 조회수")
private Long postViews;

@Schema(description = "활동일")
private LocalDate postActivityDate;
@Schema(description = "활동 시작일")
private LocalDate postActivityStartDate;

@Schema(description = "활동 종료일")
private LocalDate postActivityEndDate;

@Schema(description = "게시글 생성일")
private LocalDateTime postCreateDate;
Expand Down
25 changes: 25 additions & 0 deletions src/main/java/com/haedal/haedalweb/dto/response/PostSliderDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.haedal.haedalweb.dto.response;

import java.net.URL;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;


@Getter
@AllArgsConstructor
@Builder
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class PostSliderDTO {
@Schema(description = "게시글 id")
private Long postId;

@Schema(description = "게시글 제목")
private String postTitle;

@Schema(description = "게시글 대표 이미지 파일 Url")
private URL postImageUrl;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package com.haedal.haedalweb.dto.response;

import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;


@JsonInclude(JsonInclude.Include.NON_NULL)
@Getter
@AllArgsConstructor
@Builder
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class PostSummaryDTO {
@Schema(description = "게시글 id")
private Long postId;

@Schema(description = "게시글 제목")
private String postTitle;

@Schema(description = "게시글 대표 이미지 파일 Url")
private URL postImageUrl;

@Schema(description = "게시글 조회수")
private Long postViews;

@Schema(description = "활동 시작일")
private LocalDate postActivityStartDate;

@Schema(description = "활동 종료일")
private LocalDate postActivityEndDate;

@Schema(description = "게시글 생성일")
private LocalDateTime postCreateDate;

@Schema(description = "유저 아이디", example = "haedal12")
private String userId;

@Schema(description = "유저 이름", example = "조대성")
private String userName;

@Schema(description = "게시판 id")
private Long boardId;

@Schema(description = "게시판 이름")
private String boardName;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package com.haedal.haedalweb.repository;

import com.haedal.haedalweb.domain.Board;
import com.haedal.haedalweb.domain.Post;
import com.haedal.haedalweb.domain.PostType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

Expand All @@ -10,5 +14,9 @@
public interface PostRepository extends JpaRepository<Post, Long> {
boolean existsByBoardId(Long boardId);

Page<Post> findPostsByPostType(PostType postType, Pageable pageable);

Page<Post> findPostsByBoard(Board board, Pageable pageable);

Optional<Post> findByBoardIdAndId(Long boardId, Long postId);
}
117 changes: 116 additions & 1 deletion src/main/java/com/haedal/haedalweb/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,15 @@
import com.haedal.haedalweb.domain.Role;
import com.haedal.haedalweb.domain.User;
import com.haedal.haedalweb.dto.request.CreatePostDTO;
import com.haedal.haedalweb.dto.response.PostDTO;
import com.haedal.haedalweb.dto.response.PostSliderDTO;
import com.haedal.haedalweb.dto.response.PostSummaryDTO;
import com.haedal.haedalweb.exception.BusinessException;
import com.haedal.haedalweb.repository.BoardRepository;
import com.haedal.haedalweb.repository.PostRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
Expand Down Expand Up @@ -125,8 +130,78 @@ public void deletePost(Long postId) { // 이벤트, 공지사항 삭제
}

@Transactional(readOnly = true)
public void getPosts(Long boardId) {
public Page<PostSummaryDTO> getPosts(Long boardId, Pageable pageable) {
Board board = boardRepository.findById(boardId)
.orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_BOARD_ID));
Page<Post> postPage = postRepository.findPostsByBoard(board, pageable);

return postPage.map(post -> convertToPostSummaryDTO(post, board));
}

@Transactional(readOnly = true)
public Page<PostSummaryDTO> getPosts(String pType, Pageable pageable) {
PostType postType;

try {
postType = PostType.valueOf(pType.toUpperCase());
if (postType != PostType.NOTICE && postType != PostType.EVENT)
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
throw new BusinessException(ErrorCode.NOT_FOUND_POST_TYPE);
}

Page<Post> postPage = postRepository.findPostsByPostType(postType, pageable);

return postPage.map(post -> convertToPostSummaryDTO(post));
}

@Transactional
public PostDTO getPost(Long postId) {
Post post = postRepository.findById(postId)
.orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_POST_ID));

post.setViews(post.getViews()+1);
postRepository.save(post);

PostDTO postDTO;
if (post.getPostType() == PostType.ACTIVITY) {
postDTO = PostDTO.builder()
.postId(post.getId())
.postTitle(post.getTitle())
.postContent(post.getContent())
.postImageUrl(s3Service.generatePreSignedGetUrl(post.getImageUrl()))
.postViews(post.getViews())
.postActivityStartDate(post.getActivityStartDate())
.postActivityEndDate(post.getActivityEndDate())
.userId(post.getUser().getId())
.userName(post.getUser().getName())
.boardId(post.getBoard().getId())
.boardName(post.getBoard().getName())
.build();

return postDTO;
}

postDTO = PostDTO.builder()
.postId(post.getId())
.postTitle(post.getTitle())
.postContent(post.getContent())
.postImageUrl(s3Service.generatePreSignedGetUrl(post.getImageUrl()))
.postViews(post.getViews())
.postActivityStartDate(post.getActivityStartDate())
.postActivityEndDate(post.getActivityEndDate())
.userId(post.getUser().getId())
.userName(post.getUser().getName())
.build();

return postDTO;
}

@Transactional(readOnly = true)
public Page<PostSliderDTO> getSliderPosts(Pageable pageable) {
Page<Post> postPage = postRepository.findPostsByPostType(PostType.EVENT, pageable);

return postPage.map((post) -> convertToPostSliderDTO(post));
}

private void validateAuthorityOfPostManagement(User loggedInUser, User postCreator, User boardCreator) {
Expand All @@ -141,4 +216,44 @@ private void validateAuthorityOfPostManagement(User loggedInUser, User postCreat
throw new BusinessException(ErrorCode.FORBIDDEN_UPDATE);
}
}

private PostSummaryDTO convertToPostSummaryDTO(Post post, Board board) {
return PostSummaryDTO.builder()
.postId(post.getId())
.postTitle(post.getTitle())
.postViews(post.getViews())
.postActivityStartDate(post.getActivityStartDate())
.postActivityEndDate(post.getActivityEndDate())
.postCreateDate(post.getCreateDate())
.userId(post.getUser().getId())
.userName(post.getUser().getName())
.boardId(board.getId())
.boardName(board.getName())
.build();
}

private PostSummaryDTO convertToPostSummaryDTO(Post post) {
PostSummaryDTO postSummaryDTO = PostSummaryDTO.builder()
.postId(post.getId())
.postTitle(post.getTitle())
.postViews(post.getViews())
.postActivityStartDate(post.getActivityStartDate())
.postActivityEndDate(post.getActivityEndDate())
.postCreateDate(post.getCreateDate())
.userId(post.getUser().getId())
.userName(post.getUser().getName())
.build();

return postSummaryDTO;
}

private PostSliderDTO convertToPostSliderDTO(Post post) {
PostSliderDTO postSliderDTO = PostSliderDTO.builder()
.postId(post.getId())
.postTitle(post.getTitle())
.postImageUrl(s3Service.generatePreSignedGetUrl(post.getImageUrl()))
.build();

return postSliderDTO;
}
}
Loading

0 comments on commit b358508

Please sign in to comment.