Skip to content

Commit

Permalink
Merge pull request #113 from Developer-Wikis/feature/#109
Browse files Browse the repository at this point in the history
Feature/#109
  • Loading branch information
dhkstnaos authored Dec 2, 2022
2 parents 8782b78 + 441bcc7 commit 978a943
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 66 deletions.
Original file line number Diff line number Diff line change
@@ -1,37 +1,45 @@
package com.developer.wiki.question.command.application.comment;

import com.developer.wiki.common.exception.BadRequestException;
import com.developer.wiki.oauth.User;
import com.developer.wiki.oauth.UserRepository;
import com.developer.wiki.question.command.application.dto.CreateCommentRequest;
import com.developer.wiki.question.command.domain.*;
import com.developer.wiki.question.command.domain.Comment;
import com.developer.wiki.question.command.domain.CommentRepository;
import com.developer.wiki.question.command.domain.EntityNotFoundException;
import com.developer.wiki.question.command.domain.Question;
import com.developer.wiki.question.command.domain.QuestionRepository;
import com.developer.wiki.question.util.CommentConverter;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
@Transactional
@RequiredArgsConstructor
public class CommentCreateService {

private final CommentRepository commentRepository;
private final QuestionRepository questionRepository;
private final UserRepository userRepository;

public Long create(Long questionId, CreateCommentRequest createCommentRequest, Long userId) {
Question question = questionRepository.findById(questionId)
.orElseThrow(EntityNotFoundException::new);
return Objects.isNull(userId) ? createdByAnonymous(createCommentRequest, question)
: createdByUser(createCommentRequest, userId, question);
: createdByUser(createCommentRequest, userRepository.findById(userId)
.orElseThrow(() -> new BadRequestException("유저가 존재하지 않습니다.")), question);
}

private Long createdByAnonymous(CreateCommentRequest createCommentRequest, Question question) {
Comment comment = CommentConverter.toComment(createCommentRequest, question);
return commentRepository.save(comment).getId();
}

private Long createdByUser(CreateCommentRequest createCommentRequest, Long userId,
private Long createdByUser(CreateCommentRequest createCommentRequest, User user,
Question question) {
Comment comment = CommentConverter.toCommentByUser(createCommentRequest, question, userId);
Comment comment = CommentConverter.toCommentByUser(createCommentRequest, question, user);
return commentRepository.save(comment).getId();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.developer.wiki.question.command.application.comment;

import com.developer.wiki.common.exception.UnAuthorizedException;
import com.developer.wiki.question.command.application.dto.PasswordRequest;
import com.developer.wiki.question.command.domain.Comment;
import com.developer.wiki.question.command.domain.CommentRepository;
Expand All @@ -9,8 +8,6 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
@Transactional
@RequiredArgsConstructor
Expand All @@ -20,15 +17,7 @@ public class CommentDeleteService {

public void delete(Long id, PasswordRequest passwordRequest, Long userId) {
Comment comment = commentRepository.findById(id).orElseThrow(EntityNotFoundException::new);
checkAuthorization(userId, comment);
comment.matchPassword(passwordRequest.getPassword());
commentRepository.delete(comment);
}

private void checkAuthorization(Long userId, Comment comment) {
if ((!Objects.isNull(comment.getUserId()) && Objects.isNull(userId)) || (
Objects.isNull(comment.getUserId()) && !Objects.isNull(userId))) {
throw new UnAuthorizedException("권한이 필요합니다.");
}
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
package com.developer.wiki.question.command.application.comment;

import com.developer.wiki.common.exception.UnAuthorizedException;
import com.developer.wiki.question.command.application.dto.ModifyCommentRequest;
import com.developer.wiki.question.command.domain.Comment;
import com.developer.wiki.question.command.domain.CommentRepository;
import com.developer.wiki.question.command.domain.EntityNotFoundException;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
@Transactional
@RequiredArgsConstructor
Expand All @@ -20,17 +18,11 @@ public class CommentModifyService {

public void modify(Long id, ModifyCommentRequest modifyCommentRequest, Long userId) {
Comment comment = commentRepository.findById(id).orElseThrow(EntityNotFoundException::new);
checkAuthorization(userId, comment);
comment.matchPassword(modifyCommentRequest.getPassword());
comment.changePassword(modifyCommentRequest.getPassword());
comment.changeContent(modifyCommentRequest.getContent());
}

private void checkAuthorization(Long userId, Comment comment) {
if ((!Objects.isNull(comment.getUserId()) && Objects.isNull(userId)) || (
Objects.isNull(comment.getUserId()) && !Objects.isNull(userId))) {
throw new UnAuthorizedException("권한이 필요합니다.");
if (Objects.isNull(userId)) {
comment.matchPassword(modifyCommentRequest.getPassword());
comment.changePassword(modifyCommentRequest.getPassword());
}
comment.changeContent(modifyCommentRequest.getContent());
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@
import com.developer.wiki.question.command.domain.Comment;
import com.developer.wiki.question.command.domain.CommentRepository;
import com.developer.wiki.question.command.domain.EntityNotFoundException;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
Expand All @@ -21,7 +20,7 @@ public class CommentPasswordCheckService {
public boolean checkPassword(Long id, PasswordRequest passwordRequest, Long userId) {
Comment comment = commentRepository.findById(id).orElseThrow(EntityNotFoundException::new);
//Null이 아니면서, id도 맞지 않을때
if (!Objects.isNull(userId) && !userId.equals(comment.getUserId())) {
if (!Objects.isNull(userId) && !userId.equals(comment.getUser().getId())) {
throw new UnAuthorizedException("수정 권한이 없습니다.");
}
return comment.checkPassword(passwordRequest.getPassword());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
package com.developer.wiki.question.command.application.dto;

import javax.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotBlank;

@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CreateCommentRequest {

@NotBlank(message = "닉네임은 null일 수 없습니다.")
private String nickname;
@NotBlank(message = "비밀번호는 null일 수 없습니다.")
private String password;
@NotBlank(message = "내용은 null일 수 없습니다.")
private String content;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
package com.developer.wiki.question.command.domain;

import com.developer.wiki.oauth.User;
import com.developer.wiki.question.util.PasswordEncrypter;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Table(name = "comment")
@Getter
Expand Down Expand Up @@ -38,8 +46,8 @@ public class Comment {
@ManyToOne
@JoinColumn(name = "question_id")
private Question question;
@Column(name = "user_id")
private Long userId = null;
@ManyToOne
private User user;

public Comment(String nickname, String password, String content, Question question) {
this.nickname = nickname;
Expand All @@ -48,17 +56,14 @@ public Comment(String nickname, String password, String content, Question questi
this.commentRole = CommentRole.ANONYMOUS;
this.question = question;
this.createdAt = LocalDateTime.now();
this.userId = null;
}

public Comment(String nickname, String password, String content, Question question, Long userId) {
this.nickname = nickname;
this.password = password;
public Comment(String content, Question question, User user) {
this.content = content;
this.commentRole = CommentRole.USER;
this.question = question;
this.createdAt = LocalDateTime.now();
this.userId = userId;
this.user = user;
}

public void matchPassword(String password) {
Expand All @@ -83,7 +88,4 @@ public void changeContent(String content) {
this.content = content;
}

public Long getUserId() {
return userId;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,13 @@ public Page<SummaryQuestionResponse> findPageByUserId(Pageable pageable, String
question.getMainCategory(), question.getSubCategory(), question.getViewCount(),
question.getCommentCount(), question.getCreatedAt(), isBookmarked);
}).collect(Collectors.toList());
return new PageImpl<>(summaryQuestionResponses, pageable, questions.size());
long total = jpaQueryFactory.select(question).from(question)
.leftJoin(question.bookmarks)
.where(mainCategoryEq(mainCategory), subCategoryEq(mainCategory, subCategory),
question.isApproved.isTrue()).orderBy(question.id.asc()).offset(pageable.getOffset())
.limit(pageable.getPageSize()).distinct()
.fetchCount();
return new PageImpl<>(summaryQuestionResponses, pageable, total);
}

@Override
Expand All @@ -66,7 +72,13 @@ public Page<SummaryQuestionResponse> findBookmarkByUserId(Pageable pageable, Str
question.getMainCategory(), question.getSubCategory(), question.getViewCount(),
question.getCommentCount(), question.getCreatedAt(), isBookmarked);
}).collect(Collectors.toList());
return new PageImpl<>(summaryQuestionResponses, pageable, questions.size());
long total = jpaQueryFactory.select(question).from(question)
.leftJoin(question.bookmarks)
.where(question.bookmarks.any().userId.eq(userId), mainCategoryEq(mainCategory),
subCategoryEq(mainCategory, subCategory), question.isApproved.isTrue())
.orderBy(question.id.asc()).offset(pageable.getOffset()).limit(pageable.getPageSize() + 1)
.distinct().fetchCount();
return new PageImpl<>(summaryQuestionResponses, pageable, total);
}

@Override
Expand Down Expand Up @@ -100,7 +112,12 @@ public Page<SummaryQuestionResponse> findPageByUserIdAndKeyword(Pageable pageabl
question.getMainCategory(), question.getSubCategory(), question.getViewCount(),
question.getCommentCount(), question.getCreatedAt(), isBookmarked);
}).collect(Collectors.toList());
return new PageImpl<>(summaryQuestionResponses, pageable, questions.size());
long total = jpaQueryFactory.select(question).from(question)
.leftJoin(question.bookmarks)
.where(keywordListContains(keyword), question.isApproved.isTrue())
.orderBy(question.id.asc()).offset(pageable.getOffset()).limit(pageable.getPageSize())
.distinct().fetchCount();
return new PageImpl<>(summaryQuestionResponses, pageable, total);
}

private BooleanExpression mainCategoryEq(String mainCategory) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
import com.developer.wiki.oauth.User;
import com.developer.wiki.question.command.application.comment.CommentCreateService;
import com.developer.wiki.question.command.application.dto.CreateCommentRequest;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/questions/{questionId}/comments")
Expand All @@ -21,7 +23,7 @@ public class CommentCreateController {
@PostMapping
public ResponseEntity<Long> create(@AuthenticationPrincipal User currentUser,
@PathVariable Long questionId,
@RequestBody @Valid CreateCommentRequest createCommentRequest) {
@RequestBody CreateCommentRequest createCommentRequest) {
Long userId = Objects.isNull(currentUser) ? null : currentUser.getId();
Long id = commentCreateService.create(questionId, createCommentRequest,userId);
return ResponseEntity.ok(id);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package com.developer.wiki.question.query.application;

import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDateTime;

@Getter
@Builder
@NoArgsConstructor
Expand All @@ -18,7 +17,10 @@ public class SummaryCommentResponse {
private String username;
private String role;
private Long userId;
private String profileUrl;
private String content;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDateTime createdAt;


}
Original file line number Diff line number Diff line change
@@ -1,31 +1,35 @@
package com.developer.wiki.question.util;

import com.developer.wiki.common.exception.BadRequestException;
import com.developer.wiki.oauth.User;
import com.developer.wiki.question.command.application.dto.CreateCommentRequest;
import com.developer.wiki.question.command.domain.Comment;
import com.developer.wiki.question.command.domain.Question;
import com.developer.wiki.question.query.application.SummaryCommentResponse;

import java.util.Objects;

public class CommentConverter {

public static Comment toComment(CreateCommentRequest createCommentRequest, Question question) {
if (Objects.isNull(createCommentRequest.getNickname()) || Objects.isNull(
createCommentRequest.getPassword())) {
throw new BadRequestException("익명으로 등록시엔 nickname, password를 입력해야 합니다.");
}
return new Comment(createCommentRequest.getNickname(),
PasswordEncrypter.encrypt(createCommentRequest.getPassword()),
createCommentRequest.getContent(), question);
}

public static Comment toCommentByUser(CreateCommentRequest createCommentRequest,
Question question, Long userId) {
return new Comment(createCommentRequest.getNickname(),
PasswordEncrypter.encrypt(createCommentRequest.getPassword()),
createCommentRequest.getContent(), question, userId);
Question question, User user) {
return new Comment(createCommentRequest.getContent(), question, user);
}

public static SummaryCommentResponse ofSummary(Comment comment) {
return SummaryCommentResponse.builder().id(comment.getId()).username(comment.getNickname())
.role(comment.getCommentRole().name())
.userId(Objects.isNull(comment.getId()) ? null : comment.getUserId())
.userId(Objects.isNull(comment.getUser()) ? null : comment.getUser().getId())
.profileUrl(Objects.isNull(comment.getUser()) ? null : comment.getUser().getProfileUrl())
.content(comment.getContent()).createdAt(comment.getCreatedAt()).build();
}
}

0 comments on commit 978a943

Please sign in to comment.