Skip to content

Commit

Permalink
Merge pull request #83 from Leets-Official/refactor-#82
Browse files Browse the repository at this point in the history
Refactor: 이미지 도메인 로직 수정
  • Loading branch information
KoungQ authored Jul 31, 2024
2 parents c3dd6cd + 53f2b5d commit c85f6db
Show file tree
Hide file tree
Showing 16 changed files with 79 additions and 101 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package leets.weeth.domain.account.dto;

import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;

import java.util.List;
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/leets/weeth/domain/account/entity/Receipt.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package leets.weeth.domain.account.entity;

import jakarta.persistence.*;
import leets.weeth.domain.file.entity.File;
import leets.weeth.domain.file.converter.FileListConverter;
import leets.weeth.global.common.entity.BaseEntity;
import lombok.*;

Expand All @@ -24,8 +24,8 @@ public class Receipt extends BaseEntity {

private String description;

@OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<File> images;
@Convert(converter = FileListConverter.class)
private List<String> images;

private LocalDate date;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import leets.weeth.domain.account.dto.ReceiptDTO;
import leets.weeth.domain.account.entity.Account;
import leets.weeth.domain.account.entity.Receipt;
import leets.weeth.domain.file.entity.File;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingConstants;
Expand All @@ -14,16 +13,10 @@
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface ReceiptMapper {

@Mapping(target = "images", expression = "java( toUrls(receipt.getImages()) )")
ReceiptDTO.Response to(Receipt receipt);

@Mapping(target = "id", ignore = true)
@Mapping(target = "description", source = "dto.description")
@Mapping(target = "account", source = "account")
Receipt from(ReceiptDTO.Spend dto, Account account, List<File> images);

default List<String> toUrls(List<File> images) {
return images.stream()
.map(File::getUrl)
.toList();
}
Receipt from(ReceiptDTO.Spend dto, Account account, List<String> images);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import leets.weeth.domain.account.mapper.ReceiptMapper;
import leets.weeth.domain.account.repository.AccountRepository;
import leets.weeth.domain.account.repository.ReceiptRepository;
import leets.weeth.domain.file.entity.File;
import leets.weeth.domain.file.service.FileService;
import leets.weeth.global.common.error.exception.custom.AccountNotFoundException;
import leets.weeth.global.common.error.exception.custom.ReceiptNotFoundException;
Expand All @@ -31,7 +30,7 @@ public void spend(ReceiptDTO.Spend dto, Integer cardinal, List<MultipartFile> fi
Account account = accountRepository.findByCardinal(cardinal)
.orElseThrow(AccountNotFoundException::new);

List<File> images = fileService.uploadFiles(files);
List<String> images = fileService.uploadFiles(files);

Receipt receipt = mapper.from(dto, account, images);
receiptRepository.save(receipt);
Expand Down
14 changes: 5 additions & 9 deletions src/main/java/leets/weeth/domain/event/entity/Event.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@
import jakarta.persistence.*;
import leets.weeth.domain.event.dto.RequestEvent;
import leets.weeth.domain.event.entity.enums.Type;
import leets.weeth.domain.file.entity.File;
import leets.weeth.domain.file.converter.FileListConverter;
import leets.weeth.domain.notice.dto.RequestNotice;
import leets.weeth.domain.user.entity.User;
import leets.weeth.global.common.entity.BaseEntity;
import lombok.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

Expand Down Expand Up @@ -48,8 +47,8 @@ public class Event extends BaseEntity {
@Enumerated(EnumType.STRING)
private Type type;

@OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<File> fileUrls = new ArrayList<>();
@Convert(converter = FileListConverter.class)
private List<String> files;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
Expand All @@ -67,12 +66,9 @@ public void updateFromEventDto(RequestEvent dto) {
}

// 공지 수정을 위한 메소드
public void updateFromNoticeDto(RequestNotice dto, List<File> fileUrlList) {
public void updateFromNoticeDto(RequestNotice dto, List<String> files) {
Optional.ofNullable(dto.title()).ifPresent(title -> this.title = title);
Optional.ofNullable(dto.content()).ifPresent(content -> this.content = content);
Optional.ofNullable(fileUrlList).ifPresent(files -> {
this.fileUrls.clear();
this.fileUrls.addAll(files);
});
this.files = files;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package leets.weeth.domain.file.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;

import java.io.IOException;
import java.util.List;

public class FileListConverter implements AttributeConverter<List<String>, String> {

private static final ObjectMapper mapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);

@Override
public String convertToDatabaseColumn(List<String> attribute) {
try {
return mapper.writeValueAsString(attribute);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException();
}
}

@Override
public List<String> convertToEntityAttribute(String dbData) {
try {
return mapper.readValue(dbData, new TypeReference<>() {});
} catch (IOException e) {
throw new IllegalArgumentException();
}
}
}
24 changes: 0 additions & 24 deletions src/main/java/leets/weeth/domain/file/entity/File.java

This file was deleted.

This file was deleted.

34 changes: 12 additions & 22 deletions src/main/java/leets/weeth/domain/file/service/FileService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,14 @@

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PutObjectRequest;
import leets.weeth.domain.file.repository.FileRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import leets.weeth.domain.file.entity.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

Expand All @@ -21,37 +18,30 @@
@RequiredArgsConstructor
public class FileService {

private final FileRepository fileRepository;

@Value("${cloud.aws.s3.bucket}")
private String bucketName;

private final AmazonS3 s3Client;

public List<File> uploadFiles(List<MultipartFile> files) {
public List<String> uploadFiles(List<MultipartFile> files) {
// 다중 업로드 && 리스트 ","을 기준으로 하나의 문자열 반환
// files 갯수 0 이면 반환 ""
if(files == null || files.isEmpty())
return List.of();

List<File> results = new ArrayList<>();

for (MultipartFile file : files) {
java.io.File fileObj = convertMultiPartFileToFile(file);
String originalFilename = file.getOriginalFilename();
String extension = getFileExtension(originalFilename);
String fileName = UUID.randomUUID() + "." + extension;
return files.parallelStream()
.map(file -> {
java.io.File fileObj = convertMultiPartFileToFile(file);
String originalFilename = file.getOriginalFilename();
String extension = getFileExtension(originalFilename);
String fileName = UUID.randomUUID() + "." + extension;

log.info("uploadFile fileName: {}", fileName);
s3Client.putObject(new PutObjectRequest(bucketName, fileName, fileObj));
fileObj.delete();
File newFile = new File(s3Client.getUrl(bucketName, fileName).toString());
s3Client.putObject(new PutObjectRequest(bucketName, fileName, fileObj));
fileObj.delete();


fileRepository.save(newFile);
results.add(newFile);
}
return results;
return s3Client.getUrl(bucketName, fileName).getPath();
})
.toList();
}

private java.io.File convertMultiPartFileToFile(MultipartFile file) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package leets.weeth.domain.notice.dto;

import leets.weeth.domain.event.entity.enums.Type;
import leets.weeth.domain.file.entity.File;
import lombok.Builder;

import java.time.LocalDateTime;
Expand All @@ -16,6 +15,6 @@ public record ResponseNotice(
LocalDateTime modifiedAt,
String userName,
Type type,
List<File> fileUrls
List<String> fileUrls
) {
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package leets.weeth.domain.notice.mapper;

import leets.weeth.domain.event.entity.Event;
import leets.weeth.domain.file.entity.File;
import leets.weeth.domain.notice.dto.RequestNotice;
import leets.weeth.domain.notice.dto.ResponseNotice;
import leets.weeth.domain.user.entity.User;
Expand Down Expand Up @@ -32,5 +31,5 @@ public interface NoticeMapper {
@Mapping(target = "type", expression = "java( leets.weeth.domain.event.entity.enums.Type.NOTICE)"),
@Mapping(target = "id", ignore = true)
})
Event fromNoticeDto(RequestNotice dto, List<File> fileUrls, User user);
Event fromNoticeDto(RequestNotice dto, List<String> files, User user);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import leets.weeth.domain.event.entity.Event;
import leets.weeth.domain.event.entity.enums.Type;
import leets.weeth.domain.event.repository.EventRepository;
import leets.weeth.domain.file.entity.File;
import leets.weeth.domain.file.service.FileService;
import leets.weeth.domain.notice.dto.RequestNotice;
import leets.weeth.domain.notice.dto.ResponseNotice;
Expand Down Expand Up @@ -40,7 +39,7 @@ public void createNotice(RequestNotice requestNotice, List<MultipartFile> files,
User user = userRepository.findById(userId)
.orElseThrow(UserNotFoundException::new);

List<File> fileUrls = fileService.uploadFiles(files);
List<String> fileUrls = fileService.uploadFiles(files);
eventRepository.save(noticeMapper.fromNoticeDto(requestNotice, fileUrls, user));
}

Expand Down Expand Up @@ -76,9 +75,9 @@ public void updateNotice(Long noticeId, RequestNotice requestNotice, List<Multip
.orElseThrow(NoticeNotFoundException::new);

validateNoticeOwner(oldNotice, userId);
List<File> fileUrls = fileService.uploadFiles(files);
List<String> urls = fileService.uploadFiles(files);

oldNotice.updateFromNoticeDto(requestNotice, fileUrls);
oldNotice.updateFromNoticeDto(requestNotice, urls);
}

// 공지 삭제
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package leets.weeth.domain.post.dto;

import jakarta.validation.constraints.NotBlank;
import leets.weeth.domain.file.entity.File;
import leets.weeth.domain.post.entity.Post;
import lombok.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
Expand All @@ -24,7 +24,7 @@ public class ResponsePostDTO {
private String content;
@NotBlank
private LocalDateTime time;
private List<File> fileUrls;
private List<String> fileUrls;
private List<ResponseCommentDTO> comments;
@NotBlank
private Long commentCount;
Expand All @@ -37,7 +37,7 @@ public static ResponsePostDTO createResponsePostDTO(Post post) {
.title(post.getTitle())
.content(post.getContent())
.time(post.getTime())
.fileUrls(post.getFileUrls())
.fileUrls(post.getFiles())
.comments(post.getParentComments()
.stream()
.map(ResponseCommentDTO::createResponseCommentDto)
Expand Down
17 changes: 9 additions & 8 deletions src/main/java/leets/weeth/domain/post/entity/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotEmpty;
import leets.weeth.domain.file.entity.File;
import leets.weeth.domain.file.converter.FileListConverter;
import leets.weeth.domain.post.dto.RequestPostDTO;
import leets.weeth.domain.user.entity.User;
import leets.weeth.global.common.entity.BaseEntity;
import lombok.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -41,25 +42,25 @@ public class Post extends BaseEntity {
private List<Comment> parentComments = new ArrayList<>();

LocalDateTime time;
@OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<File> fileUrls = new ArrayList<>();

public static Post createPost(RequestPostDTO dto, User user, List<File> urls){
@Convert(converter = FileListConverter.class)
private List<String> files = new ArrayList<>();

public static Post createPost(RequestPostDTO dto, User user, List<String> files){

return Post.builder()
.user(user)
.title(dto.getTitle())
.content(dto.getContent())
.time(null)
.fileUrls(urls)
.files(files)
.build();
}

public void updatePost(RequestPostDTO dto, List<File> newUrls) {
public void updatePost(RequestPostDTO dto, List<String> files) {
this.title = dto.getTitle();
this.content = dto.getContent();
this.fileUrls.clear(); // 기존 파일 제거
this.fileUrls.addAll(newUrls); // 새로운 url 추가
this.files = files;
}

public static Long calculateTotalComments(Post post) {
Expand Down
Loading

0 comments on commit c85f6db

Please sign in to comment.