Skip to content

Commit

Permalink
entity 계층 dto변환 로직 분리
Browse files Browse the repository at this point in the history
calendar 관련 예외처리
  • Loading branch information
juhhoho committed Mar 25, 2024
1 parent dacf8e1 commit 9cf6dd4
Show file tree
Hide file tree
Showing 16 changed files with 345 additions and 71 deletions.
3 changes: 3 additions & 0 deletions JWT/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ dependencies {
// // Spring Security
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

//
implementation 'org.springframework.boot:spring-boot-starter-validation'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package JWTLogIn.JWT.user.advice;

import JWTLogIn.JWT.user.dto.error.ErrorResultDTO;
import JWTLogIn.JWT.user.exception.BadRequestException;
import JWTLogIn.JWT.user.exception.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice(basePackages = "JWTLogIn.JWT.user.controller")
public class EventControllerAdvice {

@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorResultDTO> notFoundExHandler(NotFoundException e){
ErrorResultDTO errorResult = new ErrorResultDTO("NOT_FOUND", e.getMessage());
return new ResponseEntity<>(errorResult, HttpStatus.NOT_FOUND);
}

@ExceptionHandler(BadRequestException.class)
public ResponseEntity<ErrorResultDTO> badRequestException(BadRequestException e) {
ErrorResultDTO errorResult = new ErrorResultDTO("BAD_REQUEST", e.getMessage());
return new ResponseEntity<>(errorResult, HttpStatus.BAD_REQUEST);
}

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler
public ResponseEntity<ErrorResultDTO> baseException(Exception e){
ErrorResultDTO errorResult = new ErrorResultDTO("INTERNAL_SERVER_ERROR", e.getMessage());
return new ResponseEntity<>(errorResult, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

88 changes: 59 additions & 29 deletions JWT/src/main/java/JWTLogIn/JWT/user/controller/EventController.java
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
package JWTLogIn.JWT.user.controller;

import JWTLogIn.JWT.user.dto.event.EventDTO;
import JWTLogIn.JWT.user.dto.event.EventBriefDTO;
import JWTLogIn.JWT.user.exception.BadRequestException;
import JWTLogIn.JWT.user.dto.event.EventDetailDTO;
import JWTLogIn.JWT.user.dto.event.PostEventDTO;
import JWTLogIn.JWT.user.dto.event.PutEventDTO;
import JWTLogIn.JWT.user.dto.event.UpdateEventDTO;
import JWTLogIn.JWT.user.exception.NotFoundException;
import JWTLogIn.JWT.user.service.event.EventServiceImpl;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequiredArgsConstructor
Expand All @@ -25,45 +26,74 @@ public class EventController {
private final EventServiceImpl eventServiceImpl;

@GetMapping("/calendar")
public ResponseEntity<List<EventDTO>> calendar_home(@RequestParam("year") int year, @RequestParam("month") int month){
return ResponseEntity.ok(eventServiceImpl.findMonthlyEvents(year, month));
public ResponseEntity<List<EventBriefDTO>> calendar_main(
@RequestParam("year") int year, @RequestParam("month") int month, @RequestParam(name = "day", defaultValue = "0") int day){
// 예외처리: 2020~현재 연도를 벗어나는 연도 대해 예외
if(year < 2020 || year >(int)LocalDateTime.now().getYear()){
throw new BadRequestException("년도 입력 오류");
}
// 예외처리: 1~12월을 벗어나는 월에 대해 예외
if(month < 1 || month >12){
throw new BadRequestException("월 입력 오류");
}
if(day > getLastDay(month) || day < 0){
throw new BadRequestException("날짜 입력 오류");
}


// day==0 이면 일정보가 필요없어서 디폴트 값이 할당된것
if(day == 0){
return ResponseEntity.ok(eventServiceImpl.findMonthlyEvents(year, month));
}
return ResponseEntity.ok(eventServiceImpl.findDayEvents(year, month, day));
}

@GetMapping("/calendar/{event_id}")
public ResponseEntity<EventDTO> calendar_detail(@PathVariable("event_id")Long id){
public ResponseEntity<EventDetailDTO> calendar_detail(@PathVariable("event_id")Long id){
// 예외처리: event_id를 pk로 갖지 않으면 예외
if (!eventServiceImpl.checkById(id)){
throw new NotFoundException("존재하지 않는 이벤트");
}
return ResponseEntity.ok(eventServiceImpl.findDayEvent(id));
}
@PostMapping("/calendar/post")
public ResponseEntity<?> calendar_post(@Validated @RequestBody PostEventDTO postEventDTO, BindingResult bindingResult) throws Exception {
@PostMapping("/calendar")
public ResponseEntity<?> calendar_post(@Valid @RequestBody PostEventDTO postEventDTO, BindingResult bindingResult) {
// 예외처리: PostEventDTO 대한 입력 정보 오류
if (bindingResult.hasErrors()) {
// 유효성 검사 실패 시 클라이언트에게 오류 응답 반환
List<ObjectError> errors = bindingResult.getAllErrors();
List<String> errorMessages = errors.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
return ResponseEntity.badRequest().body(errorMessages);
throw new BadRequestException("글 게시 입력 정보 오류");
}
if(postEventDTO.getStartDate().compareTo(postEventDTO.getEndDate()) > 0){
throw new BadRequestException("글 게시 시간 선후 정보 오류");
}

eventServiceImpl.eventSave(postEventDTO);
return ResponseEntity.ok().build();
}

@PutMapping("/calendar/put/{event_id}")
public ResponseEntity<?> calendar_put(@Validated @RequestBody PutEventDTO putEventDTO, BindingResult bindingResult, @PathVariable("event_id") Long id) throws Exception{

@PostMapping("/calendar/{event_id}")
public ResponseEntity<?> calendar_put(@Valid @RequestBody UpdateEventDTO updateEventDTO, BindingResult bindingResult, @PathVariable("event_id") Long id){
// 예외처리: UpdateEventDTO 대한 입력 정보 오류
if (bindingResult.hasErrors()) {
// 유효성 검사 실패 시 클라이언트에게 오류 응답 반환
List<ObjectError> errors = bindingResult.getAllErrors();
List<String> errorMessages = errors.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
return ResponseEntity.badRequest().body(errorMessages);
throw new BadRequestException("글 수정 입력 정보 오류");
}
eventServiceImpl.eventUpdate(putEventDTO, id);
eventServiceImpl.eventUpdate(updateEventDTO, id);
return ResponseEntity.ok().build();
}
@DeleteMapping("/calendar/delete/{event_id}")
@DeleteMapping("/calendar/{event_id}")
public ResponseEntity<?> calendar_delete(@PathVariable("event_id") Long id){
// 예외처리: event_id를 pk로 갖지 않으면 예외
if (!eventServiceImpl.checkById(id)){
throw new NotFoundException("존재하지 않는 이벤트");
}
eventServiceImpl.eventDelete(id);
return ResponseEntity.ok().build();
}

//------------------------------------------------------------------------------------------

// 이달의 마지막 날을 구하는 로직
public int getLastDay(int month) {
YearMonth yearMonth = YearMonth.of(LocalDateTime.now().getYear(), month);
return yearMonth.lengthOfMonth();
}
}
11 changes: 11 additions & 0 deletions JWT/src/main/java/JWTLogIn/JWT/user/dto/error/ErrorResultDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package JWTLogIn.JWT.user.dto.error;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class ErrorResultDTO {
private String code;
private String message;
}
25 changes: 25 additions & 0 deletions JWT/src/main/java/JWTLogIn/JWT/user/dto/event/EventBriefDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package JWTLogIn.JWT.user.dto.event;

import JWTLogIn.JWT.user.entity.Enum.EventType;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class EventBriefDTO {
private String title;
private LocalDateTime startDate;
private LocalDateTime endDate;
private EventType eventType;
@Builder
public EventBriefDTO(String title, LocalDateTime startDate, LocalDateTime endDate, EventType eventType) {
this.title = title;
this.startDate = startDate;
this.endDate = endDate;
this.eventType = eventType;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@
import java.time.LocalDateTime;
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class EventDTO {
public class EventDetailDTO {
private String title;
private String description;
private String url;
private LocalDateTime startDate;
private LocalDateTime endDate;
private EventType eventType;
@Builder
public EventDTO(String title, String description, String url, LocalDateTime startDate, LocalDateTime endDate, EventType eventType) {
public EventDetailDTO(String title, String description, String url, LocalDateTime startDate, LocalDateTime endDate, EventType eventType) {
this.title = title;
this.description = description;
this.url = url;
Expand Down
15 changes: 15 additions & 0 deletions JWT/src/main/java/JWTLogIn/JWT/user/dto/event/PostEventDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,37 @@

import JWTLogIn.JWT.user.entity.Enum.EventType;
import JWTLogIn.JWT.user.entity.EventEntity;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.lang.Nullable;

import java.time.LocalDateTime;

@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class PostEventDTO {

@Size(min=1)
private String title;

private String description;

private String url;

@NotNull
private LocalDateTime startDate;

@NotNull
private LocalDateTime endDate;

@NotNull
private EventType eventType;

@Builder
public PostEventDTO(String title, String description, String url, LocalDateTime startDate, LocalDateTime endDate, EventType eventType) {
this.title = title;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,20 @@
import java.time.LocalDateTime;
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class PutEventDTO {
public class UpdateEventDTO {
private String title;
private String description;
private String url;
private LocalDateTime startDate;
private LocalDateTime endDate;
private EventType eventType;
@Builder
public PutEventDTO(String title, String description, String url, LocalDateTime startDate, LocalDateTime endDate, EventType eventType) {
public UpdateEventDTO(String title, String description, String url, LocalDateTime startDate, LocalDateTime endDate, EventType eventType) {
this.title = title;
this.description = description;
this.url = url;
this.startDate = startDate;
this.endDate = endDate;
this.eventType = eventType;
}

}
37 changes: 18 additions & 19 deletions JWT/src/main/java/JWTLogIn/JWT/user/entity/EventEntity.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package JWTLogIn.JWT.user.entity;

import JWTLogIn.JWT.user.dto.event.EventDTO;
import JWTLogIn.JWT.user.dto.event.PutEventDTO;
import JWTLogIn.JWT.user.entity.Enum.EventType;
import jakarta.persistence.*;
import lombok.AccessLevel;
Expand Down Expand Up @@ -48,26 +46,27 @@ public EventEntity(String title, String description, String url, LocalDateTime s
this.eventType = eventType;
}

public void setTitle(String title) {
this.title = title;
}

public void setDescription(String description) {
this.description = description;
}

public void setUrl(String url) {
this.url = url;
}

public void setStartDate(LocalDateTime startDate) {
this.startDate = startDate;
}

public static EventDTO toEventDTO(EventEntity eventEntity){
EventDTO eventDTO = EventDTO.builder()
.title(eventEntity.getTitle())
.description(eventEntity.getDescription())
.url(eventEntity.getUrl())
.startDate(eventEntity.getStartDate())
.endDate(eventEntity.getEndDate())
.eventType(eventEntity.getEventType())
.build();
return eventDTO;
public void setEndDate(LocalDateTime endDate) {
this.endDate = endDate;
}

public void updateByPutEventDTO(PutEventDTO putEventDTO){
this.title = putEventDTO.getTitle();
this.description = putEventDTO.getDescription();
this.url = putEventDTO.getUrl();
this.startDate = putEventDTO.getStartDate();
this.endDate = putEventDTO.getEndDate();
this.eventType = putEventDTO.getEventType();
public void setEventType(EventType eventType) {
this.eventType = eventType;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package JWTLogIn.JWT.user.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(code= HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException{

public BadRequestException() {
super();
}

public BadRequestException(String message) {
super(message);
}

public BadRequestException(String message, Throwable cause) {
super(message, cause);
}

public BadRequestException(Throwable cause) {
super(cause);
}

protected BadRequestException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}

}
Loading

0 comments on commit 9cf6dd4

Please sign in to comment.