Skip to content

Commit

Permalink
codesquad-issue-team-05#80 refactor : issue service 리팩토링
Browse files Browse the repository at this point in the history
  • Loading branch information
DOEKYONG committed Aug 14, 2023
1 parent e980713 commit 452e86e
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static codesquad.issueTracker.global.exception.SuccessCode.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.web.bind.annotation.PostMapping;
Expand All @@ -22,8 +23,10 @@ public class IssueController {
private final IssueService issueService;

@PostMapping("/issues")
public ApiResponse<String> postIssues(@Valid @RequestBody IssueWriteRequestDto request) {
issueService.save(request);
public ApiResponse<String> postIssues(@Valid @RequestBody IssueWriteRequestDto request,
HttpServletRequest httpServletRequest) {
Long id = Long.parseLong(String.valueOf(httpServletRequest.getAttribute("userId")));
issueService.save(request, id);
return ApiResponse.success(SUCCESS.getStatus(), SUCCESS.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,16 @@ public class IssueWriteRequestDto {
@NotNull(message = "제목을 입력해주세요")
private String title;
private String content;
private List<Long> assignees;
private List<Long> labels;
private List<Long> assignees; // 1,2
private List<Long> labels; // 1,2
private Long milestoneId;
private Long userId;

public static Issue toEntity(IssueWriteRequestDto request) {
public static Issue toEntity(IssueWriteRequestDto request, Long userId) {
return Issue.builder()
.title(request.title)
.content(request.getContent())
.milestoneId(request.getMilestoneId())
.userId(request.getUserId())
.userId(userId)
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import codesquad.issueTracker.comment.service.CommentService;
import codesquad.issueTracker.global.exception.CustomException;
import codesquad.issueTracker.global.exception.ErrorCode;
import codesquad.issueTracker.issue.domain.Issue;
import codesquad.issueTracker.issue.dto.IssueWriteRequestDto;
import codesquad.issueTracker.issue.repository.IssueRepository;
import codesquad.issueTracker.label.repository.LabelRepository;
import codesquad.issueTracker.milestone.repository.MilestoneRepository;
import codesquad.issueTracker.user.repository.UserRepository;
import codesquad.issueTracker.label.service.LabelService;
import codesquad.issueTracker.milestone.service.MilestoneService;
import codesquad.issueTracker.user.service.UserService;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
Expand All @@ -24,46 +25,39 @@
public class IssueService {

private final IssueRepository issueRepository;
private final LabelRepository labelRepository;
private final UserRepository userRepository;
private final MilestoneRepository milestoneRepository;
private final LabelService labelService;
private final UserService userService;
private final MilestoneService milestoneService;
private final CommentService commentService;

@Transactional
public Long save(IssueWriteRequestDto request) {
isExistMilestone(request.getMilestoneId());
public Long save(IssueWriteRequestDto request, Long id) {
milestoneService.isExistMilestone(request.getMilestoneId());
List<Long> labels = request.getLabels();
List<Long> assignees = request.getAssignees();
Issue issue = IssueWriteRequestDto.toEntity(request);
Issue issue = IssueWriteRequestDto.toEntity(request, id);
Long savedIssueId = issueRepository.insert(issue);

// 라벨 리스트가 null 이 아니면 해당 라벨이 존재하는지 검증 후 라벨과 이슈 연결 테이블에 insert
if (labels != null) {
duplicatedId(labels);
labelService.validateLabelsId(labels);
labels.stream()
.map(label -> labelRepository.findById(label)
.orElseThrow(() -> new CustomException(ErrorCode.LABEL_FIND_FAILED)))
.map(findLabel -> issueRepository.insertLabels(savedIssueId, findLabel.getId()))
.map(findLabel -> issueRepository.insertLabels(savedIssueId, findLabel))
.collect(Collectors.toList());
}

// assignee 리스트가 null 이 아니면 assignees( 유저 id )가 존재하는지 검증 후 assignees 테이블에 insert
if (assignees != null) {
duplicatedId(assignees);
userService.validateUserIds(assignees);
assignees.stream()
.map(user -> userRepository.findById(user)
.orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_USER)))
.map(findUser -> issueRepository.insertAssignees(savedIssueId, findUser.getId()))
.map(findUser -> issueRepository.insertAssignees(savedIssueId, findUser))
.collect(Collectors.toList());
}
return savedIssueId;
}

private void isExistMilestone(Long id) {
if (!milestoneRepository.isExist(id)) {
throw new CustomException(ErrorCode.NOT_FOUND_MILESTONE);
}
}

private void duplicatedId(List<Long> list) {
Set<Long> set = new HashSet<>();
for (Long temp : list) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ public LabelResponseDto findAll() {
.forEach(label ->
labels.add(LabelVo.from(label)));
return LabelResponseDto.of(labels,
labelRepository.findMilestonesCount().orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_MILESTONE)));
labelRepository.findMilestonesCount()
.orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_MILESTONE)));
}

public void validateLabelsId(List<Long> labels) {
for (Long label : labels) {
labelRepository.findById(label).orElseThrow(() -> new CustomException(ErrorCode.LABEL_FIND_FAILED));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,10 @@ public MilestoneResponseDto findAll(MileStoneStatusDto request) {
return milestoneResponseDto;
}

public void isExistMilestone(Long id) {
if (!milestoneRepository.isExist(id)) {
throw new CustomException(ErrorCode.NOT_FOUND_MILESTONE);
}
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package codesquad.issueTracker.user.service;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
Expand Down Expand Up @@ -102,4 +103,11 @@ public void logout(HttpServletRequest request) {
.orElseThrow(() -> new CustomException(ErrorCode.DB_EXCEPTION));
}

public void validateUserIds(List<Long> assignees) {
for (Long assignee : assignees) {
userRepository.findById(assignee).orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_USER));
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class IssueIntegrationTest {

@BeforeEach
void setUp() {
Jwt jwt = jwtProvider.createJwt(Map.of("memberId", 1L));
Jwt jwt = jwtProvider.createJwt(Map.of("userId", 1L));
jwtToken = jwt.getAccessToken();
}

Expand All @@ -45,7 +45,7 @@ void setUp() {
void postIssues() throws Exception {
// given
List<Long> ids = List.of(1L, 2L);
IssueWriteRequestDto requestDto = new IssueWriteRequestDto("제목", "내용", ids, ids, 1L, 1L);
IssueWriteRequestDto requestDto = new IssueWriteRequestDto("제목", "내용", ids, ids, 1L);
String request = objectMapper.writeValueAsString(requestDto);
// when
ResultActions resultActions =
Expand Down
30 changes: 15 additions & 15 deletions be/issue/src/test/resources/data.sql
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
INSERT INTO users(email, password, profile_img, name, login_type)
VALUES ("[email protected]",
"$2a$10$m3yYBH1ZmolUrEA0IFjgFOFaIE2g7/Br9xgQKPZGRz6D20dGC2S8.",
"https://upload.wikimedia.org/wikipedia/commons/1/17/Enhydra_lutris_face.jpg",
"light", "local");
VALUES ('[email protected]',
'$2a$10$m3yYBH1ZmolUrEA0IFjgFOFaIE2g7/Br9xgQKPZGRz6D20dGC2S8.',
'https://upload.wikimedia.org/wikipedia/commons/1/17/Enhydra_lutris_face.jpg',
'light', 'local');

INSERT INTO users(email, password, profile_img, name, login_type)
VALUES ("[email protected]",
"$2a$10$SVqof3WP3MleyIdSTQdaneZEfMk8ezFgOkW2voRY.TxzNZIotChJe",
"https://upload.wikimedia.org/wikipedia/commons/1/17/Enhydra_lutris_face.jpg",
"gamgyul", "local");
VALUES ('[email protected]',
'$2a$10$SVqof3WP3MleyIdSTQdaneZEfMk8ezFgOkW2voRY.TxzNZIotChJe',
'https://upload.wikimedia.org/wikipedia/commons/1/17/Enhydra_lutris_face.jpg',
'gamgyul', 'local');

INSERT INTO users(email, password, profile_img, name, login_type)
VALUES ("[email protected]",
"$2a$10$GSAMSZ7WdI8Dvv.A.9bf7uOnRqp9E/esLRUxuwzSnb0uSgCUx4VXS",
"https://upload.wikimedia.org/wikipedia/commons/1/17/Enhydra_lutris_face.jpg",
"sio", "local");
VALUES ('[email protected]',
'$2a$10$GSAMSZ7WdI8Dvv.A.9bf7uOnRqp9E/esLRUxuwzSnb0uSgCUx4VXS',
'https://upload.wikimedia.org/wikipedia/commons/1/17/Enhydra_lutris_face.jpg',
'sio', 'local');

-- issues
INSERT INTO issues (milestone_id, user_id, title, content)
Expand All @@ -38,11 +38,11 @@ VALUES ('sprint1', '4번마일스톤', '2023-09-20', true);

-- label
INSERT INTO labels (name, description, background_color, text_color)
VALUES ("1번라벨", "설명1", "#111", "#222");
VALUES ('1번라벨', '설명1', '#111', '#222');
INSERT INTO labels (name, description, background_color, text_color)
VALUES ("2번라벨", "설명2", "#222", "#222");
VALUES ('2번라벨', '설명2', '#222', '#222');
INSERT INTO labels (name, description, background_color, text_color)
VALUES ("3번라벨", "설명3", "#333", "#222");
VALUES ('3번라벨', '설명3', '#333', '#222');

-- label_issue
INSERT INTO issues_labels (issue_id, label_id)
Expand Down

0 comments on commit 452e86e

Please sign in to comment.