Skip to content

Commit

Permalink
refactor: ImageService delete
Browse files Browse the repository at this point in the history
  • Loading branch information
Daolove0323 committed Nov 11, 2024
1 parent fe99d2a commit ae41b78
Show file tree
Hide file tree
Showing 18 changed files with 102 additions and 81 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ out/
.vscode/

### static images
/src/main/resources/staticimages/
/src/main/resources/static/images/

### env file
.env
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package org.ktc2.cokaen.wouldyouin.Image.api.dto;

import java.nio.file.Paths;
import java.time.LocalDateTime;
import lombok.Builder;
import lombok.Getter;
import org.ktc2.cokaen.wouldyouin.Image.persist.Image;
import org.ktc2.cokaen.wouldyouin._common.util.UriUtil;

@Getter
@Builder
Expand All @@ -16,10 +16,10 @@ public class ImageResponse {
private String extension;
private LocalDateTime createdDate;

public static ImageResponse from(Image image, String apiUrlHeader) {
public static ImageResponse from(Image image, String path) {
return ImageResponse.builder()
.id(image.getId())
.url(Paths.get(apiUrlHeader, image.getUrl()).toString())
.url(UriUtil.assembleFullUrl(path, image.getName()))
.size(image.getSize())
.extension(image.getExtension())
.createdDate(image.getCreatedDate())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ protected AdvertisementImage toEntity(ImageRequest imageRequest) {
return AdvertisementImage.builder()
.name(imageRequest.getUrl())
.size(imageRequest.getSize())
.extension(imageRequest.getExtension())
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ protected CurationImage toEntity(ImageRequest imageRequest) {
return CurationImage.builder()
.url(imageRequest.getUrl())
.size(imageRequest.getSize())
.extension(imageRequest.getExtension())
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ protected EventImage toEntity(ImageRequest imageRequest) {
return EventImage.builder()
.url(imageRequest.getUrl())
.size(imageRequest.getSize())
.extension(imageRequest.getExtension())
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.ktc2.cokaen.wouldyouin.Image.persist.Image;
import org.ktc2.cokaen.wouldyouin.Image.persist.ImageRepository;
import org.ktc2.cokaen.wouldyouin._common.exception.EntityNotFoundException;
import org.ktc2.cokaen.wouldyouin._common.util.UriUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
Expand All @@ -32,20 +33,6 @@ public abstract class ImageService<T extends Image> {

protected abstract T toEntity(ImageRequest imageRequest);

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

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

protected void delete(Long id) {
getById(id);
getImageRepository().deleteById(id);
}

@Transactional
public List<ImageResponse> saveImages(List<MultipartFile> images) {
return images.stream()
Expand All @@ -57,6 +44,20 @@ public List<ImageResponse> saveImages(List<MultipartFile> images) {
public void deleteImage(Long id) {
T image = getById(id);
delete(id);
imageStorageService.delete(image.getUrl());
imageStorageService.delete(getChildPath(), image.getName());
}

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

protected ImageResponse create(ImageRequest imageRequest) {
return ImageResponse.from(getImageRepository().save(toEntity(imageRequest)), UriUtil.assembleFullUrl(apiUrl, getChildPath()));
}

protected void delete(Long id) {
getById(id);
getImageRepository().deleteById(id);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,34 +21,32 @@ public class ImageStorageService {
private String parentPath;
private final RestClientUtil client;

public byte[] readFromDirectory(Path path) {
return FileUtil.readFile(Paths.get(parentPath).resolve(path));
public byte[] readFromDirectory(Path childPath) {
return FileUtil.readFile(Paths.get(parentPath).resolve(childPath));
}

public ImageRequest saveToDirectory(MultipartFile image, String subPath) {
public ImageRequest saveToDirectory(MultipartFile image, String childPath) {
String extension = FileUtil.getExtension(image);
String fileName = FileUtil.generateUuidName() + "." + extension;
String relativeFilePath = Paths.get(subPath, fileName).toString();
Path absoluteFilePath = Paths.get(parentPath, relativeFilePath);
FileUtil.saveFile(image, absoluteFilePath);
return ImageRequest.of(relativeFilePath, image.getSize(), FileUtil.getExtension(image));
String fileName = FileUtil.createRandomFileName(extension);
FileUtil.saveFile(image, Path.of(parentPath, childPath, fileName));
return ImageRequest.of(fileName, image.getSize(), extension);
}

public ImageRequest saveToDirectory(String imageUrl, String subPath) {
public ImageRequest saveToDirectory(String imageUrl, String childPath) {
byte[] response = client.get(byte[].class, imageUrl, new HttpHeaders(),
(req, rsp) -> { throw new FailedToUploadImageException("이미지 URL에 대한 요청을 실패하였습니다."); }
);
Optional.ofNullable(response).orElseThrow(
() -> new FailedToUploadImageException("응답 본문이 비어있어 이미지를 가져올 수 없습니다."));
() -> new FailedToUploadImageException("응답 본문이 비어있어 이미지를 가져올 수 없습니다.")
);
String extension = FileUtil.getExtension(imageUrl);
String fileName = FileUtil.generateUuidName() + "." + extension;
String relativeFilePath = Paths.get(subPath, fileName).toString();
Path absoluteFilePath = Paths.get(parentPath, relativeFilePath);
FileUtil.saveFile(response, absoluteFilePath);
return ImageRequest.of(relativeFilePath, (long) response.length, extension);
String fileName = FileUtil.createRandomFileName(extension);
Path path = Path.of(parentPath, childPath, fileName);
FileUtil.saveFile(response, path);
return ImageRequest.of(fileName, (long) response.length, extension);
}

public void delete(String imagePath) {
FileUtil.deleteFile(Paths.get(imagePath));
public void delete(String childPath, String fileName) {
FileUtil.deleteFile(Path.of(parentPath, childPath, fileName));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ protected MemberImage toEntity(ImageRequest imageRequest) {
return MemberImage.builder()
.url(imageRequest.getUrl())
.size(imageRequest.getSize())
.extension(imageRequest.getExtension())
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ public abstract class Image {
protected Long id;

@NotNull
@Column(name = "url")
protected String url;
@Column(name = "name")
protected String name;

@Column(name = "size")
private Long size;
Expand All @@ -42,8 +42,8 @@ public abstract class Image {
@Column(name = "created_date")
private LocalDateTime createdDate;

protected Image(String url, Long size, String extension) {
this.url = url;
protected Image(String name, Long size, String extension) {
this.name = name;
this.size = size;
this.extension = extension;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ public static void deleteFile(Path path) {
}
}

public static String generateUuidName() {
return UUID.randomUUID().toString().replace("-", "");
public static String createRandomFileName(String extension) {
return UUID.randomUUID().toString().replace("-", "") + "." + extension;
}

public static String getExtension(MultipartFile file) {
Expand Down
34 changes: 34 additions & 0 deletions src/main/java/org/ktc2/cokaen/wouldyouin/_common/util/UriUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package org.ktc2.cokaen.wouldyouin._common.util;

import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

public class UriUtil {

public static String buildUrl(String scheme, String host, String path, MultiValueMap<String, String> params) {
return UriComponentsBuilder.newInstance()
.scheme(scheme)
.host(host)
.path(path)
.queryParams(params)
.build()
.toString();
}

public static String buildUrl(String scheme, String host, String path) {
return UriComponentsBuilder.newInstance()
.scheme(scheme)
.host(host)
.path(path)
.build()
.toString();
}

public static String assembleFullUrl(String baseUrl, String... paths) {
String joinedPath = String.join("/", paths);
return UriComponentsBuilder.fromHttpUrl(baseUrl)
.path("/" + joinedPath)
.build()
.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static AdvertisementResponse from(Advertisement advertisement) {
return AdvertisementResponse.builder()
.id(advertisement.getId())
.title(advertisement.getTitle())
.imageUrl(advertisement.getAdvertisementImage().getUrl())
.imageUrl(advertisement.getAdvertisementImage().getName())
.startTime(advertisement.getStartTime())
.endTime(advertisement.getEndTime())
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.Objects;
import org.ktc2.cokaen.wouldyouin._common.util.RestClientUtil;
import org.ktc2.cokaen.wouldyouin._common.util.UriUtil;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.AccessTokenResponse;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.OauthRequest;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.OauthResourcesResponse;
Expand All @@ -12,7 +13,6 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

@Service
public class GoogleRequestService extends OauthRequestService {
Expand Down Expand Up @@ -44,22 +44,10 @@ public class GoogleRequestService extends OauthRequestService {
private final HttpHeaders loginRequestHeaders;

public GoogleRequestService(RestClientUtil restClientUtil) {

this.client = restClientUtil;

loginRequestUri = UriComponentsBuilder.newInstance()
.scheme("https")
.host(loginRequestHost)
.path(loginRequestPath)
.build(true)
.toString();

accessRequestUri = UriComponentsBuilder.newInstance()
.scheme("https")
.host(accessRequestHost)
.path(accessRequestPath)
.build(true)
.toString();
loginRequestUri = UriUtil.buildUrl("https", loginRequestHost, loginRequestPath);
accessRequestUri = UriUtil.buildUrl("https", accessRequestHost, accessRequestPath);

loginRequestHeaders = new HttpHeaders();
loginRequestHeaders.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.ktc2.cokaen.wouldyouin._common.util.RestClientUtil;
import org.ktc2.cokaen.wouldyouin._common.util.UriUtil;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.AccessTokenResponse;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.OauthRequest;
import org.ktc2.cokaen.wouldyouin.auth.application.oauth.dto.OauthResourcesResponse;
Expand All @@ -14,7 +15,8 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

@Service
public class KakaoRequestService extends OauthRequestService {
Expand Down Expand Up @@ -53,29 +55,23 @@ protected AccountType getAccountType() {
public KakaoRequestService(RestClientUtil restClientUtil) {
this.client = restClientUtil;

OauthRequest request = getOauthRequestBase();
loginRequestUri = UriComponentsBuilder.newInstance()
.scheme("https")
.host(loginRequestHost)
.path(loginRequestPath)
.queryParam("grant_type", request.getGrantType())
.queryParam("client_id", request.getClientId())
.queryParam("client_secret", request.getClientSecret())
.queryParam("code", request.getCode())
.build(true)
.toString();

accessRequestUri = UriComponentsBuilder.newInstance()
.scheme("https")
.host(accessRequestHost)
.path(accessRequestPath)
.build(true)
.toString();
loginRequestUri = UriUtil.buildUrl("https", loginRequestHost, loginRequestPath, getLoginRequestQueryParams());
accessRequestUri = UriUtil.buildUrl("https", accessRequestHost, accessRequestPath);

loginRequestHeaders = new HttpHeaders();
loginRequestHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
}

protected MultiValueMap<String, String> getLoginRequestQueryParams() {
OauthRequest request = getOauthRequestBase();
var queries = new LinkedMultiValueMap<String, String>();
queries.add("grant_type", request.getGrantType());
queries.add("client_id", request.getClientId());
queries.add("client_secret", request.getClientSecret());
queries.add("code", request.getCode());
return queries;
}

protected HttpHeaders getAccessRequestHeaders(AccessTokenResponse authenticationResponse) {
HttpHeaders accessRequestHeaders = new HttpHeaders();
accessRequestHeaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public static CurationCardResponse from(CurationCard curationCard) {
.content(curationCard.getContent())
.imageUrls(
curationCard.getCurationImages().stream()
.map(CurationImage::getUrl)
.map(CurationImage::getName)
.toList()
)
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ private static MemberResponseBuilder responseBase(BaseMember baseMember) {
.memberId(baseMember.getId())
.nickname(baseMember.getNickname())
.phoneNumber(baseMember.getPhone())
.profileUrl(baseMember.getProfileImage().getUrl());
.profileUrl(baseMember.getProfileImage().getName());
}

// TODO: normal member임에도 불구, curator 형식이 호출되는 현상 수정필요
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public static EventHostResponse from(Host host) {
.nickname(host.getNickname())
.email(host.getEmail())
.phone(host.getPhone())
.profileImageUrl(host.getProfileImage().getUrl())
.profileImageUrl(host.getProfileImage().getName())
.intro(host.getIntro())
.likes(host.getLikes())
.hashtags(host.getHashTagList())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,6 @@ protected BaseMember(AccountType accountType, MemberType memberType, String emai
}

public String getProfileImageUrl() {
return profileImage.getUrl();
return profileImage.getName();
}
}

0 comments on commit ae41b78

Please sign in to comment.