Skip to content

Commit fc15eff

Browse files
committed
그룹 투표 상세조회 api
1 parent f51663d commit fc15eff

File tree

2 files changed

+77
-70
lines changed

2 files changed

+77
-70
lines changed

polling-app-server/src/main/java/com/example/polls/controller/GroupPollController.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,12 @@ public ResponseEntity<PagedResponse<PollResponse>> getAllPollInGroup(@PathVariab
4040
return ResponseEntity.ok(response);
4141
}
4242

43+
@GetMapping("/{pollId}")
44+
public ResponseEntity<PollResponse> getPollByIdInGroup(@PathVariable Long groupId,
45+
@PathVariable Long pollId,
46+
@CurrentUser UserPrincipal userPrincipal){
47+
PollResponse response = pollService.getPollByIdInGroup(pollId, groupId, userPrincipal);
48+
return ResponseEntity.ok(response);
49+
}
50+
4351
}

polling-app-server/src/main/java/com/example/polls/service/PollService.java

Lines changed: 69 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -50,36 +50,38 @@ public class PollService {
5050
@Autowired
5151
private GroupMemberRepository groupMemberRepository;
5252

53-
54-
public PagedResponse<PollResponse> getAllPolls(UserPrincipal currentUser, int page, int size) {
55-
validatePageNumberAndSize(page, size);
56-
57-
// Retrieve Polls
58-
Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createdAt");
59-
Page<Poll> polls = pollRepository.findAll(pageable);
60-
53+
private PagedResponse<PollResponse> mapPollPagetoPageResponse(UserPrincipal currentUser, Page<Poll> polls) {
6154
if(polls.getNumberOfElements() == 0) {
6255
return new PagedResponse<>(Collections.emptyList(), polls.getNumber(),
6356
polls.getSize(), polls.getTotalElements(), polls.getTotalPages(), polls.isLast());
6457
}
6558

66-
// Map Polls to PollResponses containing vote counts and poll creator details
6759
List<Long> pollIds = polls.map(Poll::getId).getContent();
6860
Map<Long, Long> choiceVoteCountMap = getChoiceVoteCountMap(pollIds);
6961
Map<Long, Long> pollUserVoteMap = getPollUserVoteMap(currentUser, pollIds);
7062
Map<Long, User> creatorMap = getPollCreatorMap(polls.getContent());
7163

72-
List<PollResponse> pollResponses = polls.map(poll -> {
73-
return ModelMapper.mapPollToPollResponse(poll,
74-
choiceVoteCountMap,
75-
creatorMap.get(poll.getCreatedBy()),
76-
pollUserVoteMap == null ? null : pollUserVoteMap.getOrDefault(poll.getId(), null));
77-
}).getContent();
64+
List<PollResponse> pollResponses = polls.map(poll -> ModelMapper.mapPollToPollResponse(
65+
poll,
66+
choiceVoteCountMap,
67+
creatorMap.get(poll.getCreatedBy()),
68+
pollUserVoteMap == null ? null : pollUserVoteMap.getOrDefault(poll.getId(), null)
69+
)).getContent();
7870

7971
return new PagedResponse<>(pollResponses, polls.getNumber(),
8072
polls.getSize(), polls.getTotalElements(), polls.getTotalPages(), polls.isLast());
8173
}
8274

75+
public PagedResponse<PollResponse> getAllPolls(UserPrincipal currentUser, int page, int size) {
76+
validatePageNumberAndSize(page, size);
77+
78+
// Retrieve Polls
79+
Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createdAt");
80+
Page<Poll> polls = pollRepository.findAll(pageable);
81+
82+
return mapPollPagetoPageResponse(currentUser, polls);
83+
}
84+
8385
public PagedResponse<PollResponse> getAllPollsInGroup(Long groupId, UserPrincipal userPrincipal, int page, int size) {
8486
//그룹 유효성검사
8587
Group group = groupRepository.findById(groupId)
@@ -95,28 +97,7 @@ public PagedResponse<PollResponse> getAllPollsInGroup(Long groupId, UserPrincipa
9597
//결과 데이터 가져오기
9698
Page<Poll> polls = pollRepository.findByGroupId(groupId, pageable);
9799

98-
if(polls.getNumberOfElements() == 0) {
99-
return new PagedResponse<>(Collections.emptyList(), polls.getNumber(),
100-
polls.getSize(), polls.getTotalElements(), polls.getTotalPages(), polls.isLast());
101-
}
102-
103-
// Map Polls to PollResponses containing vote counts and poll creator details
104-
List<Long> pollIds = polls.map(Poll::getId).getContent();
105-
Map<Long, Long> choiceVoteCountMap = getChoiceVoteCountMap(pollIds);
106-
Map<Long, Long> pollUserVoteMap = getPollUserVoteMap(userPrincipal, pollIds);
107-
Map<Long, User> creatorMap = getPollCreatorMap(polls.getContent());
108-
109-
110-
List<PollResponse> pollResponses = polls.map(poll -> {
111-
return ModelMapper.mapPollToPollResponse(poll,
112-
choiceVoteCountMap,
113-
creatorMap.get(poll.getCreatedBy()),
114-
pollUserVoteMap == null ? null : pollUserVoteMap.getOrDefault(poll.getId(), null));
115-
}).getContent();
116-
117-
return new PagedResponse<>(pollResponses, polls.getNumber(),
118-
polls.getSize(), polls.getTotalElements(), polls.getTotalPages(), polls.isLast());
119-
100+
return mapPollPagetoPageResponse(userPrincipal, polls);
120101
}
121102

122103
public PagedResponse<PollResponse> getPollsCreatedBy(String username, UserPrincipal currentUser, int page, int size) {
@@ -188,57 +169,50 @@ public PagedResponse<PollResponse> getPollsVotedBy(String username, UserPrincipa
188169
}
189170

190171

191-
public Poll createPoll(PollRequest pollRequest) {
172+
private Poll createPollInternal(PollRequest request, Long createdBy, Group group) {
192173
Poll poll = new Poll();
193-
poll.setQuestion(pollRequest.getQuestion());
194-
195-
pollRequest.getChoices().forEach(choiceRequest -> {
196-
poll.addChoice(new Choice(choiceRequest.getText()));
197-
});
198-
199-
Instant now = Instant.now();
200-
Instant expirationDateTime = now.plus(Duration.ofDays(pollRequest.getPollLength().getDays()))
201-
.plus(Duration.ofHours(pollRequest.getPollLength().getHours()));
174+
poll.setQuestion(request.getQuestion());
202175

203-
poll.setExpirationDateTime(expirationDateTime);
204-
205-
return pollRepository.save(poll);
206-
}
176+
if (createdBy != null) {
177+
poll.setCreatedBy(createdBy);
178+
}
207179

208-
//그룹 투표 생성
209-
public Poll createPollInGroup(Long groupId, PollRequest request, UserPrincipal userPrincipal) {
210-
//그룹 엔티티 조회
211-
Group group = groupRepository.findById(groupId)
212-
.orElseThrow(() -> new ResourceNotFoundException("Group", "id", groupId));
213-
//투표 객체 생성
214-
Poll poll = new Poll();
215-
poll.setQuestion(request.getQuestion());
180+
if (group != null) {
216181
poll.setGroup(group);
217-
poll.setCreatedBy(userPrincipal.getId());
182+
}
218183

219-
//선택지 추가
220184
request.getChoices().forEach(choiceRequest -> {
221185
poll.addChoice(new Choice(choiceRequest.getText()));
222186
});
223187

224-
//종료시간 계산
225188
Instant now = Instant.now();
226189
Instant expirationDateTime = now.plus(Duration.ofDays(request.getPollLength().getDays()))
227190
.plus(Duration.ofHours(request.getPollLength().getHours()));
228191
poll.setExpirationDateTime(expirationDateTime);
229192

230-
231-
//저장
232193
return pollRepository.save(poll);
233194
}
234195

235196

236-
public PollResponse getPollById(Long pollId, UserPrincipal currentUser) {
237-
Poll poll = pollRepository.findById(pollId).orElseThrow(
238-
() -> new ResourceNotFoundException("Poll", "id", pollId));
197+
public Poll createPoll(PollRequest pollRequest) {
198+
return createPollInternal(pollRequest, null, null);
199+
}
239200

240-
// Retrieve Vote Counts of every choice belonging to the current poll
241-
List<ChoiceVoteCount> votes = voteRepository.countByPollIdGroupByChoiceId(pollId);
201+
//그룹 투표 생성
202+
public Poll createPollInGroup(Long groupId, PollRequest request, UserPrincipal userPrincipal) {
203+
//그룹 엔티티 조회
204+
Group group = groupRepository.findById(groupId)
205+
.orElseThrow(() -> new ResourceNotFoundException("Group", "id", groupId));
206+
boolean isMember = groupMemberRepository.existsByUserIdAndGroupId(userPrincipal.getId(), groupId);
207+
if(!isMember) {
208+
throw new BadRequestException("해당 그룹에 가입된 자만 투표할 수 있습니다.");
209+
}
210+
//저장
211+
return createPollInternal(request, userPrincipal.getId(), group);
212+
}
213+
214+
public PollResponse buildPollResponse(Poll poll, UserPrincipal currentUser) {
215+
List<ChoiceVoteCount> votes = voteRepository.countByPollIdGroupByChoiceId(poll.getId());
242216

243217
Map<Long, Long> choiceVotesMap = votes.stream()
244218
.collect(Collectors.toMap(ChoiceVoteCount::getChoiceId, ChoiceVoteCount::getVoteCount));
@@ -250,13 +224,38 @@ public PollResponse getPollById(Long pollId, UserPrincipal currentUser) {
250224
// Retrieve vote done by logged in user
251225
Vote userVote = null;
252226
if(currentUser != null) {
253-
userVote = voteRepository.findByUserIdAndPollId(currentUser.getId(), pollId);
227+
userVote = voteRepository.findByUserIdAndPollId(currentUser.getId(), poll.getId());
254228
}
255229

256230
return ModelMapper.mapPollToPollResponse(poll, choiceVotesMap,
257231
creator, userVote != null ? userVote.getChoice().getId(): null);
258232
}
259233

234+
public PollResponse getPollById(Long pollId, UserPrincipal currentUser) {
235+
Poll poll = pollRepository.findById(pollId).orElseThrow(
236+
() -> new ResourceNotFoundException("Poll", "id", pollId));
237+
238+
return buildPollResponse(poll, currentUser);
239+
}
240+
241+
public PollResponse getPollByIdInGroup(Long pollId, Long groupId, UserPrincipal currentUser) {
242+
Group group = groupRepository.findById(groupId)
243+
.orElseThrow(() -> new ResourceNotFoundException("Group", "id", groupId));
244+
boolean isMember = groupMemberRepository.existsByUserIdAndGroupId(currentUser.getId(), groupId);
245+
if(!isMember) {
246+
throw new BadRequestException("해당 그룹에 가입된 사용자만 투표를 조회할 수 있습니다.");
247+
}
248+
249+
Poll poll = pollRepository.findById(pollId).orElseThrow(
250+
() -> new ResourceNotFoundException("Poll", "id", pollId)
251+
);
252+
if(poll.getGroup() != null && !poll.getGroup().getId().equals(groupId)) {
253+
throw new BadRequestException("해당 투표는 요청한 그룹에 속하지 않습니다.");
254+
}
255+
256+
return buildPollResponse(poll, currentUser);
257+
}
258+
260259
public PollResponse castVoteAndGetUpdatedPoll(Long pollId, VoteRequest voteRequest, UserPrincipal currentUser) {
261260
Poll poll = pollRepository.findById(pollId)
262261
.orElseThrow(() -> new ResourceNotFoundException("Poll", "id", pollId));

0 commit comments

Comments
 (0)