Skip to content

Commit

Permalink
[Weekly/11/All/refactor ] 전반적인 코드 리팩토링
Browse files Browse the repository at this point in the history
  • Loading branch information
Daolove0323 authored Nov 9, 2024
1 parent 146df9f commit b19cb75
Show file tree
Hide file tree
Showing 39 changed files with 597 additions and 370 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public ResponseEntity<byte[]> getImage(@PathVariable String domain, @PathVariabl
System.out.println(Paths.get("static/images", domain, path));
return ResponseEntity.status(HttpStatus.OK).body(Files.readAllBytes(resource.getFile().toPath()));
} catch (IOException e) {
throw new FailToReadImageException();
throw new FailToReadImageException("이미지를 읽어오는데 실패했습니다.");
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package org.ktc2.cokaen.wouldyouin.Image.application;

import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.ktc2.cokaen.wouldyouin.Image.api.ImageDomain;
import org.ktc2.cokaen.wouldyouin.Image.api.dto.ImageRequest;
import org.ktc2.cokaen.wouldyouin.Image.persist.AdvertisementImage;
import org.ktc2.cokaen.wouldyouin.Image.persist.AdvertisementImageRepository;
import org.ktc2.cokaen.wouldyouin.Image.persist.ImageRepository;
import org.ktc2.cokaen.wouldyouin._common.exception.EntityParamIsNullException;
import org.ktc2.cokaen.wouldyouin.advertisement.persist.Advertisement;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -54,8 +52,6 @@ public AdvertisementImage saveAndCreateImage(MultipartFile image) {

@Transactional
public void setAd(AdvertisementImage image, Advertisement ad) {
Optional.ofNullable(image).orElseThrow(() -> new EntityParamIsNullException(getImageDomain().name() + " image"));
Optional.ofNullable(ad).orElseThrow(() -> new EntityParamIsNullException("advertisement"));
image.setAdvertisement(ad);
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package org.ktc2.cokaen.wouldyouin.Image.application;

import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.ktc2.cokaen.wouldyouin.Image.api.ImageDomain;
import org.ktc2.cokaen.wouldyouin.Image.api.dto.ImageRequest;
import org.ktc2.cokaen.wouldyouin.Image.persist.CurationImage;
import org.ktc2.cokaen.wouldyouin.Image.persist.CurationImageRepository;
import org.ktc2.cokaen.wouldyouin.Image.persist.ImageRepository;
import org.ktc2.cokaen.wouldyouin._common.exception.EntityParamIsNullException;
import org.ktc2.cokaen.wouldyouin.curation.persist.CurationCard;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -47,8 +45,6 @@ protected CurationImage toEntity(ImageRequest imageRequest) {

@Transactional
public void setCuration(CurationImage image, CurationCard curationCard) {
Optional.ofNullable(image).orElseThrow(() -> new EntityParamIsNullException(getImageDomain().name() + " image"));
Optional.ofNullable(curationCard).orElseThrow(() -> new EntityParamIsNullException("curationCard"));
image.setCurationCard(curationCard);
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package org.ktc2.cokaen.wouldyouin.Image.application;

import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.ktc2.cokaen.wouldyouin.Image.api.ImageDomain;
import org.ktc2.cokaen.wouldyouin.Image.api.dto.ImageRequest;
import org.ktc2.cokaen.wouldyouin.Image.persist.EventImage;
import org.ktc2.cokaen.wouldyouin.Image.persist.EventImageRepository;
import org.ktc2.cokaen.wouldyouin.Image.persist.ImageRepository;
import org.ktc2.cokaen.wouldyouin._common.exception.EntityParamIsNullException;
import org.ktc2.cokaen.wouldyouin.event.persist.Event;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -44,8 +42,6 @@ protected EventImage toEntity(ImageRequest imageRequest) {

@Transactional
public void setEvent(EventImage image, Event event) {
Optional.ofNullable(image).orElseThrow(() -> new EntityParamIsNullException(getImageDomain().name() + " image"));
Optional.ofNullable(event).orElseThrow(() -> new EntityParamIsNullException("event"));
image.setEvent(event);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,15 @@ public abstract class ImageService<T extends Image> {

public T getById(Long id) {
return getImageRepository().findById(id)
.orElseThrow(() -> new EntityNotFoundException(getImageDomain().name() + " Image"));
.orElseThrow(() -> new EntityNotFoundException(getImageDomain().name() + " 이미지를 찾을 수 없습니다."));
}

protected ImageResponse create(ImageRequest imageRequest) {
return ImageResponse.from(getImageRepository().save(toEntity(imageRequest)), domainName);
}

protected void delete(Long id) {
getImageRepository().findById(id)
.orElseThrow(() -> new EntityNotFoundException(getImageDomain().name() + " Image"));
getById(id);
getImageRepository().deleteById(id);
}

Expand All @@ -59,9 +58,8 @@ public List<ImageResponse> saveAndCreateImages(List<MultipartFile> images) {

@Transactional
public void deleteAndDelete(Long id) {
String url = getImageRepository().findById(id)
.orElseThrow(() -> new EntityNotFoundException(getImageDomain().name() + " Image")).getUrl();
T image = getById(id);
delete(id);
imageStorage.delete(url);
imageStorage.delete(image.getUrl());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public String save(MultipartFile image, String subPath) {
Files.createDirectories(path.getParent());
Files.write(path, image.getBytes());
} catch (IOException ex) {
throw new FailedToUploadImageException();
throw new FailedToUploadImageException("이미지를 업로드하는데 실패했습니다.");
}
return subPath + "/" + fileName;
}
Expand All @@ -54,7 +54,7 @@ public ImageRequest save(String imageUrl, String subPath) {
Files.write(path, response.getBody());
}
} catch (IOException ex) {
throw new FailedToUploadImageException();
throw new FailedToUploadImageException("URL을 통해 이미지를 저장하는데 실패했습니다.");
}
String url = subPath + "/" + fileName;
return ImageRequest.of(url, size, getExtension(imageUrl));
Expand All @@ -64,7 +64,7 @@ public void delete(String imagePath) {
try {
Files.deleteIfExists(Paths.get(imagePath));
} catch (IOException ex) {
throw new FailedToDeleteImageException();
throw new FailedToDeleteImageException("이미지를 삭제하는데 실패했습니다.");
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
package org.ktc2.cokaen.wouldyouin.Image.application;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.ktc2.cokaen.wouldyouin.Image.api.ImageDomain;
import org.ktc2.cokaen.wouldyouin.Image.api.dto.ImageRequest;
import org.ktc2.cokaen.wouldyouin.Image.persist.ImageRepository;
import org.ktc2.cokaen.wouldyouin.Image.persist.MemberImage;
import org.ktc2.cokaen.wouldyouin.Image.persist.MemberImageRepository;
import org.ktc2.cokaen.wouldyouin._common.exception.EntityParamIsNullException;
import org.ktc2.cokaen.wouldyouin.member.persist.BaseMember;
import org.ktc2.cokaen.wouldyouin.member.persist.BaseMemberRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClient;

@Service
@RequiredArgsConstructor
Expand Down Expand Up @@ -55,8 +47,6 @@ protected MemberImage toEntity(ImageRequest imageRequest) {

@Transactional
public void setBaseMember(MemberImage image, BaseMember member) {
Optional.ofNullable(image).orElseThrow(() -> new EntityParamIsNullException(getImageDomain().name() + " image"));
Optional.ofNullable(member).orElseThrow(() -> new EntityParamIsNullException("baseMember"));
image.setBaseMember(member);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
@Getter
public enum ErrorCode {

UNEXPECTED(HttpStatus.BAD_REQUEST.value(), "-1", "Unexpected exception occurred"),
UNEXPECTED(HttpStatus.BAD_REQUEST.value(), "-1", "예상치 못한 오류가 발생했습니다."),

ENTITY_NOT_FOUND(HttpStatus.NOT_FOUND.value(), "-10404", "Can not find a %s Entity"),
ENTITY_NOT_FOUND(HttpStatus.NOT_FOUND.value(), "-10404", "엔티티를 찾을 수 없습니다."),

NO_LEFT_SEAT(HttpStatus.BAD_REQUEST.value(), "-10400", "No left seat"),
NO_LEFT_SEAT(HttpStatus.BAD_REQUEST.value(), "-10400", "남은 좌석이 부족합니다."),

INVALID_INPUT_VALUE(HttpStatus.BAD_REQUEST.value(), "-20400", "Invalid Input Value"),

Expand All @@ -20,8 +20,6 @@ public enum ErrorCode {

UNAUTHORIZED(HttpStatus.UNAUTHORIZED.value(), "-20400", "Unauthorized, %s."),

ENTITY_PARAM_IS_NULL(HttpStatus.BAD_REQUEST.value(), "-20400", "%s is null"),

FAIL_TO_UPLOAD_IMAGE(HttpStatus.CONFLICT.value(), "-20400", "Fail to upload image"),

FAIL_TO_DELETE_IMAGE(HttpStatus.CONFLICT.value(), "-20400", "Fail to delete image"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class GlobalExceptionHandler {

@ExceptionHandler(BusinessException.class)
public ResponseEntity<ApiResponseBody<Void>> handleBusinessException(BusinessException e) {
return ApiResponse.error(e.getErrorCode());
return ApiResponse.error(e.getErrorCode(), e.getMessage());
}

@ExceptionHandler(MethodArgumentNotValidException.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,4 @@ public BusinessException(String message, ErrorCode errorCode) {
super(message);
this.errorCode = errorCode;
}

public BusinessException(ErrorCode errorCode, Object... args) {
super(String.format(errorCode.getMessage(), args));
this.errorCode = errorCode;
}
}

This file was deleted.

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

public class EntityNotFoundException extends BusinessException {

public EntityNotFoundException(String notFoundedEntityName) {
super(ErrorCode.ENTITY_NOT_FOUND, notFoundedEntityName);
public EntityNotFoundException(String message) {
super(message, ErrorCode.ENTITY_NOT_FOUND);
}
}

This file was deleted.

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

public class FailToReadImageException extends BusinessException {

public FailToReadImageException() {
super(ErrorCode.FAIL_TO_READ_IMAGE);
public FailToReadImageException(String message) {
super(message, ErrorCode.FAIL_TO_READ_IMAGE);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

public class FailedToDeleteImageException extends BusinessException {

public FailedToDeleteImageException() {
super(ErrorCode.FAIL_TO_DELETE_IMAGE, ErrorCode.FAIL_TO_DELETE_IMAGE.getMessage());
public FailedToDeleteImageException(String message) {
super(message, ErrorCode.FAIL_TO_DELETE_IMAGE);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
public class FailedToPayException extends BusinessException {

public FailedToPayException(String message) {
super(ErrorCode.FAIL_TO_PAY, message);
super(message, ErrorCode.FAIL_TO_PAY);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

public class FailedToUploadImageException extends BusinessException {

public FailedToUploadImageException() {
super(ErrorCode.FAIL_TO_UPLOAD_IMAGE, ErrorCode.FAIL_TO_UPLOAD_IMAGE.getMessage());
public FailedToUploadImageException(String message) {
super(message, ErrorCode.FAIL_TO_UPLOAD_IMAGE);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

public class NoLeftSeatException extends BusinessException {

public NoLeftSeatException() {
super(ErrorCode.NO_LEFT_SEAT);
public NoLeftSeatException(String message) {
super(message, ErrorCode.NO_LEFT_SEAT);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ public class UnauthorizedException extends BusinessException {
public UnauthorizedException(String message) {
super(message, ErrorCode.UNAUTHORIZED);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package org.ktc2.cokaen.wouldyouin._common.vo;

import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UserLocation {

@NotNull(message = "위도 값은 필수입니다.")
@Min(value = -90, message = "위도는 -90 이상이어야 합니다.")
@Max(value = 90, message = "위도는 90 이하여야 합니다.")
private Double latitude;

@NotNull(message = "경도 값은 필수입니다.")
@Min(value = -180, message = "경도는 -180 이상이어야 합니다.")
@Max(value = 180, message = "경도는 180 이하여야 합니다.")
private Double longitude;
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,31 +22,37 @@ public class AdvertisementService {
private final AdvertisementRepository adRepository;
private final AdvertisementImageService adImageService;

@Transactional(readOnly = true)
public List<AdvertisementResponse> getAllActiveAdvertisements() {
return adRepository.findAllActiveAdvertisements(LocalDateTime.now()).stream()
.map(AdvertisementResponse::from).toList();
@Transactional
public Advertisement getByIdOrThrow(Long adId) {
return adRepository.findById(adId)
.orElseThrow(() -> new EntityNotFoundException("해당하는 광고를 찾을 수 없습니다."));
}

@Transactional(readOnly = true)
public AdvertisementResponse getAdvertisementByAdId(Long adId) {
return AdvertisementResponse.from(adRepository.findById(adId).orElseThrow(() -> new EntityNotFoundException("Advertisement")));
return AdvertisementResponse.from(getByIdOrThrow(adId));
}

@Transactional(readOnly = true)
public List<AdvertisementResponse> getAllActiveAdvertisements() {
return adRepository.findAllActiveAdvertisements(LocalDateTime.now()).stream()
.map(AdvertisementResponse::from).toList();
}

// Todo: 롤백될 경우, 저장한 이미지 삭제
@Transactional
public AdvertisementResponse create(AdvertisementRequest adRequest, MultipartFile image) {
AdvertisementImage adImage = adImageService.saveAndCreateImage(image);
Advertisement ad = adRepository.save(adRequest.toEntity(adImage));
adImage.setAdvertisement(ad);
adImageService.setAd(adImage, ad);
return AdvertisementResponse.from(ad);
}

// Todo: 수정될 때 이미지가 null인 경우 기존 이미지로 대체하는 로직 프론트와 협의
// Todo: 롤백될 경우, 저장한 이미지 삭제
@Transactional
public AdvertisementResponse update(Long adId, AdvertisementRequest adRequest, MultipartFile multipartFile) {
Advertisement ad = adRepository.findById(adId).orElseThrow(() -> new EntityNotFoundException("Advertisement"));
Advertisement ad = getByIdOrThrow(adId);
Optional.ofNullable(multipartFile).ifPresentOrElse(
image -> {
adImageService.deleteAndDelete(ad.getAdvertisementImage().getId());
Expand All @@ -64,7 +70,7 @@ public AdvertisementResponse update(Long adId, AdvertisementRequest adRequest, M

@Transactional
public void delete(Long adId) {
Advertisement ad = adRepository.findById(adId).orElseThrow(() -> new EntityNotFoundException("Advertisement"));
Advertisement ad = getByIdOrThrow(adId);
adImageService.deleteAndDelete(ad.getAdvertisementImage().getId());
adRepository.deleteById(adId);
}
Expand Down
Loading

0 comments on commit b19cb75

Please sign in to comment.