Skip to content

Commit

Permalink
[TDC-23] poll delete 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
yerimkoko committed Jan 3, 2024
1 parent 86f71a3 commit 40573c6
Show file tree
Hide file tree
Showing 15 changed files with 146 additions and 25 deletions.
Original file line number Diff line number Diff line change
@@ -1,32 +1,34 @@
package com.threedollar.config.advice;

import com.threedollar.common.exception.dto.response.ApiResponse;
import lombok.RequiredArgsConstructor;
import com.threedollar.common.exception.exception.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;



import static com.threedollar.common.exception.ErrorCode.E400_INVALID;
import static java.util.stream.Collectors.joining;

@Slf4j
@RequiredArgsConstructor
@RestControllerAdvice
public class ControllerExceptionAdvice {

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
private ApiResponse<Object> handleBadRequest(BindException exception) {
String errorMessage = exception.getBindingResult().getFieldErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(joining("\n"));
log.error("BindException: {}", errorMessage);
return ApiResponse.error(E400_INVALID, errorMessage);
private ApiResponse<Object> handleBadRequest(BindException e) {
log.error(e.getMessage(), e);
return ApiResponse.error(E400_INVALID, e.getMessage());
}

@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NotFoundException.class)
private ApiResponse<Object> handleNotFound(NotFoundException e) {
log.error(e.getErrorCode().getMessage(), e);
return ApiResponse.error(e.getErrorCode(), e.getMessage());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.threedollar.config.advice;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class WebDataBinderConfig {

@InitBinder
public void initBinder(WebDataBinder binder) {
binder.initDirectFieldAccess();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@
import com.threedollar.service.poll.service.PollService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
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 javax.validation.Valid;
Expand All @@ -22,12 +26,22 @@ public class PollController {

@Operation(summary = "[투표] 투표를 합니다", description = "유저 혹은 사장님이 투표를 추가합니다.")
@PostMapping("/v1/poll")
public ApiResponse<Long> createPoll(@Valid PollCreateRequest request,
@NotNull AccountType accountType,
@NotBlank String requestId) {
Long pollId = pollService.addPoll(request, accountType, requestId);
public ApiResponse<Long> createPoll(@Valid @RequestBody PollCreateRequest request,
@NotNull @RequestParam AccountType accountType,
@NotBlank @RequestParam String accountId) {
Long pollId = pollService.addPoll(request, accountType, accountId);
return ApiResponse.success(pollId);
}

@Operation(summary = "[투표] 투표를 삭제합니다", description = "유저 혹은 사장님이 투표를 제거합니다.")
@DeleteMapping("/v1/poll/{pollId}")
public ApiResponse<String> deletePoll(@PathVariable Long pollId,
@RequestParam AccountType accountType,
@RequestParam String accountId) {
pollService.deletePoll(pollId, accountType, accountId);
return ApiResponse.OK;

}


}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebMvcConfigurationSupport {
public class SwaggerConfiguration {

@Bean
public Docket swaggerAPI() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ public Long addPoll(PollCreateRequest request, AccountType accountType, String a
return pollRepository.save(poll).getId();
}

@Transactional
public void deletePoll(Long pollId, AccountType accountType, String accountId) {
Poll poll = PollServiceHelper.getPollByIdAndAccountType(pollRepository, pollId, accountType, accountId);
poll.delete();
}


public List<PollTypeResponse> getPollTypes() {
return PollCategory.pollTypeList().stream()
.map(PollTypeResponse::of)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.threedollar.service.poll.service;

import com.threedollar.common.exception.exception.NotFoundException;
import com.threedollar.domain.AccountType;
import com.threedollar.domain.poll.Poll;
import com.threedollar.domain.poll.repository.PollRepository;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PollServiceHelper {

public static Poll getPollByIdAndAccountType(PollRepository pollRepository, Long pollId, AccountType accountType, String accountId) {
Poll poll = pollRepository.findByPollIdAndAccount(pollId, accountType, accountId);
if(poll == null) {
throw new NotFoundException(String.format("(%s)에 해당하는 투표는 존재하지 않습니다.", pollId));
}
return poll;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.threedollar.domain.AccountType;
import com.threedollar.domain.poll.Poll;
import com.threedollar.domain.poll.PollCategory;
import com.threedollar.domain.poll.PollStatus;
import com.threedollar.domain.poll.repository.PollRepository;
import com.threedollar.service.poll.dto.request.PollCreateRequest;
import com.threedollar.service.poll.service.PollService;
Expand Down Expand Up @@ -57,12 +58,38 @@ void clean_up() {
// then
List<Poll> polls = pollRepository.findAll();
assertThat(polls).hasSize(1);
assertThat(polls.get(0).getPollCategory()).isEqualTo(pollCategory);
assertThat(polls.get(0).getAccountId()).isEqualTo(accountId);
assertThat(polls.get(0).getTitle()).isEqualTo(title);
assertPoll(polls.get(0), pollCategory, accountId, title, content);

}

@Test
void 투표를_삭제합니다() {
// given
AccountType accountType = AccountType.USER_ACCOUNT;
PollCategory pollCategory = PollCategory.BEST_FOOD;
String accountId = "1L";
String title = "제목";
String content = "내용";
LocalDateTime startDateTime = LocalDateTime.of(2024,1,2,19,0);
LocalDateTime endDateTime = LocalDateTime.of(2024, 1, 31, 18,59);
Poll poll = pollRepository.save(Poll.newInstance(pollCategory, title, content, accountType, accountId, startDateTime, endDateTime));

// when
pollService.deletePoll(poll.getId(), accountType, accountId);

// then
List<Poll> polls = pollRepository.findAll();
assertThat(polls).hasSize(1);
assertThat(polls.get(0).getPollStatus()).isEqualTo(PollStatus.DELETED);


}


private void assertPoll(Poll poll, PollCategory pollCategory, String accountId, String title, String content) {
assertThat(poll.getPollCategory()).isEqualTo(pollCategory);
assertThat(poll.getAccountId()).isEqualTo(accountId);
assertThat(poll.getTitle()).isEqualTo(title);
assertThat(poll.getContent()).isEqualTo(content);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

public enum ErrorCode {
E400_INVALID(HttpStatusCode.BAD_REQUEST, "BR000", "잘못된 요청입니다"),

E404_NOT_FOUND(HttpStatusCode.NOT_FOUND, "NF000", "찾을 수 없습니다"),
;

private final HttpStatusCode httpStatusCode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
public enum HttpStatusCode {

BAD_REQUEST(400),
NOT_FOUND(404),
;

private final int status;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.threedollar.common.exception.exception;

import com.threedollar.common.exception.ErrorCode;
import com.threedollar.common.exception.model.BaseException;

public class NotFoundException extends BaseException {

private static final ErrorCode DEFAULT_ERROR_CODE = ErrorCode.E404_NOT_FOUND;

public NotFoundException(String message) {
super(message, DEFAULT_ERROR_CODE);
}

public NotFoundException(String message, ErrorCode errorCode) {
super(message, errorCode);
}

public NotFoundException(String message, ErrorCode errorCode, Throwable cause) {
super(message, errorCode, cause);
}

}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Index;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -72,6 +70,10 @@ public void addOptions(List<PollOption> options) {
}
}

public void delete() {
this.pollStatus = PollStatus.DELETED;
}

private void addOption(PollOption pollOption) {
this.options.add(pollOption);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
@RequiredArgsConstructor
@Getter
public enum PollCategory {

TASTE_VS_TASTE("맛짱투표", "그만싸워 얘덜아... 먹을걸로 왜그래..."),
BEST_FOOD("가장 맛있는 음식", "참맛을 찾아서 ....")
;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.threedollar.domain.poll.repository;


import com.threedollar.domain.AccountType;
import com.threedollar.domain.poll.Poll;
import com.threedollar.domain.poll.PollCategory;

Expand All @@ -10,5 +11,7 @@ public interface PollRepositoryCustom {

List<Poll> findAllPollList(Long cursor, int size, PollCategory pollCategory);

Poll findByPollIdAndAccount(Long pollId, AccountType accountType, String accountId);


}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.threedollar.domain.AccountType;
import com.threedollar.domain.poll.Poll;
import com.threedollar.domain.poll.PollCategory;
import com.threedollar.domain.poll.PollStatus;
import lombok.RequiredArgsConstructor;

import java.util.List;
Expand All @@ -25,6 +27,16 @@ public List<Poll> findAllPollList(Long cursor, int size, PollCategory pollCatego
.fetch();
}

@Override
public Poll findByPollIdAndAccount(Long pollId, AccountType accountType, String accountId) {
return jpaQueryFactory.selectFrom(poll)
.where(poll.id.eq(pollId),
poll.accountType.eq(accountType),
poll.accountId.eq(accountId),
poll.pollStatus.eq(PollStatus.ACTIVE))
.fetchOne();
}

private BooleanExpression existedCursor(Long cursor) {
if (cursor == null) {
return null;
Expand Down

0 comments on commit 40573c6

Please sign in to comment.