Skip to content

Commit

Permalink
#82 fix : user 조회 presentation layer -> service layer 이동
Browse files Browse the repository at this point in the history
  • Loading branch information
rivkode committed Apr 29, 2024
1 parent fd088a8 commit ab9e2b4
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,12 @@
@Tag(name = "댓글 api")
public class CommentController {
private final CommentService commentService;
private final UserService userService;

@Operation(summary = "Comment 생성", description = "게시글에 댓글이 생성되며, 사용자와 시간이 포함됩니다.")
@PostMapping
public ResponseEntity<GetCommentResponse> createComment(@Valid @RequestBody CreateCommentRequest request, @LoginUser String userId) {
User user = userService.getUser(userId);

return ResponseEntity.status(HttpStatus.CREATED).body(commentService.createComment(user, request));
return ResponseEntity.status(HttpStatus.CREATED).body(commentService.createComment(userId, request));
}

@Operation(summary = "Comment 수정", description = "댓글이 요청에 대해 수정됩니다.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import com.seoultech.synergybe.domain.post.Post;
import com.seoultech.synergybe.domain.post.service.PostService;
import com.seoultech.synergybe.domain.user.User;
import com.seoultech.synergybe.domain.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -26,26 +27,30 @@ public class CommentService {
private final CommentRepository commentRepository;

private final PostService postService;
private final UserService userService;

private final NotificationService notificationService;
private final IdGenerator idGenerator;

public GetCommentResponse createComment(User user, CreateCommentRequest request) {
public GetCommentResponse createComment(String userId, CreateCommentRequest request) {
Post post = postService.findPostById(request.postId());
User user = userService.getUser(userId);
String commentId = idGenerator.generateId(IdPrefix.COMMENT);

Comment comment = Comment.builder()
.id(commentId).comment(request.comment()).post(post).user(user)
.id(commentId)
.comment(request.comment())
.post(post).user(user)
.build();


Comment savedComment = commentRepository.save(comment);
savedComment.addPost(post);
User postUser = post.getUser();
// User postUser = post.getUser();
// notificationService.send(postUser, NotificationType.COMMENT, "댓글이 생성되었습니다", post.getId());
GetCommentResponse commentResponse = GetCommentResponse.builder().build();

return commentResponse;
return GetCommentResponse.builder()
.commentId(savedComment.getId())
.build();
}

public GetCommentResponse updateComment(UpdateCommentRequest request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.seoultech.synergybe.domain.post.Post;
import com.seoultech.synergybe.domain.post.dto.request.CreatePostRequest;
import com.seoultech.synergybe.domain.post.dto.request.UpdatePostRequest;
import com.seoultech.synergybe.domain.post.dto.response.GetListPostResponse;
import com.seoultech.synergybe.domain.post.dto.response.GetPostResponse;
import com.seoultech.synergybe.domain.post.service.PostService;
import com.seoultech.synergybe.domain.user.User;
Expand All @@ -29,46 +30,41 @@
public class PostController {
private final PostService postService;

private final UserService userService;


@Operation(summary = "post 생성", description = "PostResponse가 반환되며 이미지가 함께 저장됩니다.")
@PostMapping
public ResponseEntity<GetPostResponse> createPost(@ModelAttribute CreatePostRequest request, @LoginUser String userId) {
User user = userService.getUser(userId);

return ResponseEntity.status(HttpStatus.CREATED).body(postService.createPost(user, request));
return ResponseEntity.status(HttpStatus.CREATED).body(postService.createPost(userId, request));
}

@Operation(summary = "post 수정", description = "PostResponse가 반환되며 UpdatePostRequest에 담긴 내용으로 수정됩니다.")
@PutMapping
public ResponseEntity<GetPostResponse> updatePost(@RequestBody UpdatePostRequest request, @LoginUser String userId) {
User user = userService.getUser(userId);

return ResponseEntity.status(HttpStatus.OK).body(postService.updatePost(request));
return ResponseEntity.status(HttpStatus.OK).body(postService.updatePost(userId, request));
}

@Operation(summary = "post 삭제", description = "DeletePostResponse가 반환되며, post의 isDelete = true 로 값이 변경됩니다")
@DeleteMapping(value = "/{postId}")
public ResponseEntity<Void> deletePost(@PathVariable("postId") String postId, @LoginUser String userId) {
User user = userService.getUser(userId);
postService.deletePost(userId, postId);

return ResponseEntity.noContent().build();
}

@Operation(summary = "단건 Post Get", description = "요청된 1개의 Post가 반환됩니다")
@GetMapping(value = "/{postId}")
public ResponseEntity<GetPostResponse> getPost(@PathVariable("postId") String postId, @LoginUser String userId) {
User user = userService.getUser(userId);
public ResponseEntity<GetPostResponse> getPost(@PathVariable("postId") String postId) {

return ResponseEntity.status(HttpStatus.OK).body(postService.getPost(postId));
}

@Operation(summary = "최근 Post 리스트", description = "ListPostResponse가 반환되며, end값(default로는 long 최대값)으로 마지막 조회된 postId를 전달받으며 이후 10개의 post만 반환합니다")
@GetMapping(value = "/recent")
public ResponseEntity<ListResponse<GetPostResponse>> getPosts(@Parameter(description = "마지막 조회 Id") @RequestParam(value = "end", required = false, defaultValue = "9223372036854775807") String end) {
public ResponseEntity<GetListPostResponse> getPosts(@Parameter(description = "offset") @RequestParam(value = "offset", required = false, defaultValue = "9223372036854775807") Long offset) {

return ResponseEntity.status(HttpStatus.OK).body(postService.getPostList(end));
return ResponseEntity.status(HttpStatus.OK).body(postService.getPostRecentList(offset));
}

// @Operation(summary = "팔로워의 Post", description = "팔로워의 Post가 반환됩니다")
Expand All @@ -95,26 +91,24 @@ public ResponseEntity<ListResponse<GetPostResponse>> getPostsByUser(@Parameter(d
}


@Operation(summary = "내가 좋아요한 Post", description = "좋아요한 Post가 반환됩니다")
@GetMapping(value = "/me/likes")
public ResponseEntity<ListResponse<GetPostResponse>> getLikedPosts(@LoginUser String userId) {
User user = userService.getUser(userId);
// @Operation(summary = "내가 좋아요한 Post", description = "좋아요한 Post가 반환됩니다")
// @GetMapping(value = "/me/likes")
// public ResponseEntity<> getLikedPosts(@LoginUser String userId) {
//
// return ResponseEntity.status(HttpStatus.OK).body(postService.getLikedPostList(userId));
// }

return ResponseEntity.status(HttpStatus.OK).body(postService.getLikedPostList(user));
}
// @Operation(summary = "추천 Post", description = "나의 활동을 바탕으로 Post가 추천됩니다")
// @GetMapping(value = "/recommend")
// public ResponseEntity<ListResponse<GetPostResponse>> getRecommendPosts(@Parameter(description = "마지막 Post Id") @RequestParam(value = "end", required = false, defaultValue = "0") Long end, @LoginUser String userId) {
//
// return ResponseEntity.status(HttpStatus.OK).body(postService.getRecommendPostList(userId, end));
// }

@Operation(summary = "추천 Post", description = "나의 활동을 바탕으로 Post가 추천됩니다")
@GetMapping(value = "/recommend")
public ResponseEntity<ListResponse<GetPostResponse>> getRecommendPosts(@Parameter(description = "마지막 Post Id") @RequestParam(value = "end", required = false, defaultValue = "0") Long end, @LoginUser String userId) {
User user = userService.getUser(userId);
@Operation(summary = "이주의 베스트 Post", description = "좋아요 상위 랭킹 순으로 Post가 반환됩니다")
@GetMapping(value = "/week")
public ResponseEntity<GetListPostResponse> getWeekBestPosts() {

return ResponseEntity.status(HttpStatus.OK).body(postService.getRecommendPostList(user, end));
return ResponseEntity.status(HttpStatus.OK).body(postService.getWeekBestPostList());
}

// @Operation(summary = "이주의 베스트 Post", description = "좋아요 상위 랭킹 순으로 Post가 반환됩니다")
// @GetMapping(value = "/week")
// public ResponseEntity<ListPostResponse> getWeekBestPosts(@LoginUser String userId) {
//
// return ResponseEntity.status(HttpStatus.OK).body(postService.getWeekBestPostList());
// }
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seoultech.synergybe.domain.comment.dto.response.GetCommentResponse;
import com.seoultech.synergybe.domain.common.PageInfo;
import com.seoultech.synergybe.domain.common.idgenerator.IdGenerator;
import com.seoultech.synergybe.domain.common.idgenerator.IdPrefix;
import com.seoultech.synergybe.domain.common.paging.ListResponse;
import com.seoultech.synergybe.domain.follow.service.FollowService;
import com.seoultech.synergybe.domain.post.Post;
import com.seoultech.synergybe.domain.post.dto.request.CreatePostRequest;
import com.seoultech.synergybe.domain.post.dto.request.UpdatePostRequest;
import com.seoultech.synergybe.domain.post.dto.response.GetListPostResponse;
import com.seoultech.synergybe.domain.post.dto.response.GetPostResponse;
import com.seoultech.synergybe.domain.post.exception.PostBadRequestException;
import com.seoultech.synergybe.domain.post.exception.PostNotFoundException;
import com.seoultech.synergybe.domain.post.repository.PostRepository;
import com.seoultech.synergybe.domain.postlike.service.PostLikeService;
Expand Down Expand Up @@ -48,17 +52,22 @@ public class PostService {

// private final ImageService imageService;

public GetPostResponse createPost(User user, CreatePostRequest request) {
public GetPostResponse createPost(String userId, CreatePostRequest request) {
User user = userService.getUser(userId);
if (request.files() == null) {
log.info(">> getfiles is null");
String postId = idGenerator.generateId(IdPrefix.POST);
Post post = Post.builder()
.id(postId).title(request.title()).user(user)
.id(postId)
.title(request.title())
.content(request.content())
.user(user)
.build();
Post savedPost = postRepository.save(post);
GetPostResponse getPostResponse = GetPostResponse.builder().build();

return getPostResponse;
return GetPostResponse.builder()
.postId(savedPost.getId())
.build();
// } else {
// log.info(">> getfiles is NOT NULL");
// List<MultipartFile> files = request.files();
Expand All @@ -76,58 +85,69 @@ public GetPostResponse createPost(User user, CreatePostRequest request) {
}

@Transactional
public GetPostResponse updatePost(UpdatePostRequest request) {
public GetPostResponse updatePost(String userId, UpdatePostRequest request) {
// todo
// user 검증
User user = userService.getUser(userId);

Post post = findPostById(request.postId());
validateUser(user, post);
post.updatePost(request.title(), request.content());
// List<String> imagesUrl = imageService.getImageUrlByPostId(request.getPostId());

// return PostResponse.from(updatedPost, imagesUrl);
GetPostResponse getPostResponse = GetPostResponse.builder().build();
return getPostResponse;
return GetPostResponse.builder()
.postId(post.getId())
.build();
}

public void deletePost(String postId) {
private void validateUser(User user, Post post) {
if (!post.getUser().equals(user)) {
throw new PostBadRequestException("인증되지 않은 유저입니다.");
}
}

public void deletePost(String userId, String postId) {
Post post = this.findPostById(postId);
User user = userService.getUser(userId);
validateUser(user, post);
postRepository.delete(post);
}

public Post findPostById(String postId) {
return postRepository.findById(postId)
.orElseThrow(() -> new PostNotFoundException("존재하지 않는 게시글입니다."));
}


public List<Post> findAllByFollowingIdAndEndId(String userId, Long end) {
return postRepository.findAllByFollowingIdAndEndId(userId, end);
}


public ListResponse<GetPostResponse> getLikedPostList(User user) {
List<String> postIds = postLikeService.findLikedPostIds(user);

List<Post> posts = postRepository.findAllById(postIds);

return new ListResponse(posts);
}
// public GetListPostResponse getMyLikedPostList(String userId) {
// List<Post> postList = postRepository.findAllByLikeAndDate();
//
//
// return PostMapperEntityToDto.postListToResponse(postList);
// }

public ListResponse<GetPostResponse> getPostList(String end) {
List<Post> posts = postRepository.findAllByEndId(end);
public GetListPostResponse getPostRecentList(Long offset) {
// List<Post> posts = postRepository.findAllByEndId(end);

int count = postRepository.countPostList(end);
// offset은 시작 지점
// 0부터 시작하며 다음 요청시마다 10씩 증가해야함
List<Post> posts = postRepository.findAllByCreateAtAndLimit(offset);
int totalCount = postRepository.countTotalPostSize();

boolean isNext;
boolean hasNext;
int pageSize = 10;

if (count > pageSize + 1) {
isNext = true;
if (totalCount > pageSize + offset) {
hasNext = true;
} else {
isNext = false;
hasNext = false;
}
// todo
// 썸네일이 없을 경우 없는채로 처리가 되어야 함


// return ListPostResponse.from(GetPostResponse.from(posts), isNext);
return new ListResponse(posts);
return PostMapperEntityToDto.postListToResponse(posts, hasNext);
}


Expand Down Expand Up @@ -277,7 +297,38 @@ private List<String> extractIds(String response) {
}

public GetPostResponse getPost(String postId) {
GetPostResponse getPostResponse = GetPostResponse.builder().build();
return getPostResponse;
Post post = findPostById(postId);
List<GetCommentResponse> commentResponses = post.getComments().stream()
.map(comment -> new GetCommentResponse(
comment.getId(),
comment.getUser().getId(),
comment.getPost().getId(),
comment.getComment().getContent(),
comment.getUpdateAt()
))
.toList();

return GetPostResponse.builder()
.postId(post.getId())
.title(post.getTitle().getTitle())
.content(post.getContent().getContent())
.userId(post.getUser().getId())
.likes(post.getLikes().size())
.authorName(post.getAuthorName().getAuthorName())
.createAt(post.getCreateAt())
.updateAt(post.getUpdateAt())
.commentList(commentResponses)
.build();
}

public Post findPostById(String postId) {
return postRepository.findById(postId)
.orElseThrow(() -> new PostNotFoundException("존재하지 않는 게시글입니다."));
}

public GetListPostResponse getWeekBestPostList() {
List<GetPostResponse> postList = postRepository.findAllByMostLikedAndRecentOneWeek();
PageInfo pageInfo = PageInfo.of(postList.size());
return new GetListPostResponse(postList, pageInfo);
}
}

0 comments on commit ab9e2b4

Please sign in to comment.