Skip to content

Commit

Permalink
91 게시물 수정 (#93)
Browse files Browse the repository at this point in the history
* Fix: s3에 'postId-filname' 으로 저장하도록 변경

* Fix: s3이미지 이름 수정

* Feat(#91): s3,DB 이미지 삭제, 재업로드
  • Loading branch information
dainshon authored Jul 31, 2024
1 parent 6213a03 commit 03ad37a
Show file tree
Hide file tree
Showing 11 changed files with 136 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
@Getter
@RequiredArgsConstructor
@JsonPropertyOrder({"code", "status", "message", "timestamp"})
public class BaseErrorResponse implements ResponseStatus {
public class BaseErrorResponse extends Throwable implements ResponseStatus {
private final int code;
private final int status;
private final String message;
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/inandout/backend/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.requestMatchers("/main", "/ispublic", "/password", "/check-password", "/nickname",
"/chat", "/ws/chat", "/myroom/chat","/myroom/post/{postId}/chat",
"/others/room/detail/{postId}/chat", "/myroom/addstuff",
"/myroom/post/{postId}","/others","/others/post/{postId}").authenticated());
"/myroom/post/{postId}","/others","/others/post/{postId}","/myroom/updatestuff").authenticated());

//LoginFilter 이전에 JWTFilter 등록
http.addFilterBefore(new JWTFilter(jwtUtil), LoginFilter.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ public BaseResponse<MyRoomAddStuffResponseDTO> myRoomAddStuffController(@Request
@RequestPart(value = "file") List<MultipartFile> multipartFile) {
MyRoomAddStuffResponseDTO myRoomAddStuffResponseDTO = myRoomService.addStuff(myRoomAddStuffRequestDTO, multipartFile);


return new BaseResponse<>(myRoomAddStuffResponseDTO);
}

Expand Down
44 changes: 44 additions & 0 deletions src/main/java/inandout/backend/controller/post/PostController.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@
package inandout.backend.controller.post;

import inandout.backend.common.exception.BaseException;
import inandout.backend.common.response.BaseResponse;
import inandout.backend.dto.myroom.MyRoomAddStuffRequestDTO;
import inandout.backend.dto.post.InOutRequestDTO;
import inandout.backend.dto.post.InOutResponseDTO;
import inandout.backend.dto.post.UpdateStuffRequestDTO;
import inandout.backend.entity.post.Post;
import inandout.backend.entity.post.PostImage;
import inandout.backend.repository.post.PostJPARepository;
import inandout.backend.service.myroom.S3Service;
import inandout.backend.service.post.PostService;
import inandout.backend.service.stuff.StuffService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Optional;

import static inandout.backend.common.response.status.BaseExceptionResponseStatus.BAD_REQUEST;

@RestController
@Slf4j
Expand All @@ -21,6 +34,12 @@ public class PostController {
@Autowired
public StuffService stuffService;

@Autowired
public PostJPARepository postJPARepository;

@Autowired
public S3Service s3Service;

@PostMapping("/inout")
public BaseResponse<InOutResponseDTO> inOutController(@RequestBody InOutRequestDTO inOutRequestDTO) throws Exception {
log.info("in/out");
Expand All @@ -31,4 +50,29 @@ public BaseResponse<InOutResponseDTO> inOutController(@RequestBody InOutRequestD
return new BaseResponse<>(inOutResponseDTO);
}

@PostMapping("/myroom/updatestuff")
public BaseResponse<String> updateStuffController(@RequestPart(value = "request") UpdateStuffRequestDTO updateStuffRequestDTO,
@RequestPart(value = "file") List<MultipartFile> multipartFile){
System.out.println("PostController/updateStuffController");

//게시물 찾기
Optional<Post> post = postJPARepository.findById(updateStuffRequestDTO.getPostId());
if(!post.isPresent()){
throw new BaseException(BAD_REQUEST); // 게시물 없음
}

//이미지 빼고 수정
postService.updatePost(post.get(), updateStuffRequestDTO);

//S3, DB에서 기존 이미지 삭제
postService.deleteImage(post.get());

//S3에 새로운 이미지 삽입, urls 받아오기 & DB에 저장
List<String> imageUrls = s3Service.uploadFile(multipartFile, String.valueOf(post.get().getId()));
postService.updatePostImages(post.get(), imageUrls);


return new BaseResponse<>("success");
}

}
19 changes: 19 additions & 0 deletions src/main/java/inandout/backend/dto/post/UpdateStuffRequestDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package inandout.backend.dto.post;


import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class UpdateStuffRequestDTO {

private Integer postId;
private String title;
private String inContent;
private String outContent;


}
3 changes: 2 additions & 1 deletion src/main/java/inandout/backend/jwt/JWTFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
|| request.getRequestURI().equals("/join") || request.getRequestURI().equals("/auth/verify")
|| request.getRequestURI().equals("/kakaologin/callback")
|| request.getRequestURI().equals("/kakaologin")
|| request.getRequestURI().equals("/find-password")) {
|| request.getRequestURI().equals("/find-password")
) {
filterChain.doFilter(request, response);
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,7 @@ public interface PostImageJPARepository extends JpaRepository<PostImage, Integer
@Query("SELECT pi.postImgUrl FROM PostImage pi WHERE pi.post.id = :post_id")
List<String> findUrlByPostId(@Param(value = "post_id") Integer postId);

@Query("DELETE FROM PostImage pi WHERE pi.post.id = :post_id")
void deleteByPostId(@Param(value = "post_id") Integer postId);

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

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

@Repository
@RequiredArgsConstructor
Expand Down Expand Up @@ -119,4 +120,12 @@ public Post getPostByRoodId(Integer chatRoomId) throws Exception {
return post.get(0);

}

@Transactional
public void updatePost(Integer postId, String title, String inContent, String outContent) {
em.createQuery("UPDATE Post p SET p.title = :title, p.inContent = :inContent, p.outContent = :outContent " +
"WHERE p.id = :postId").setParameter("title", title).setParameter("inContent", inContent).
setParameter("outContent", outContent).setParameter("postId", postId)
.executeUpdate();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,14 @@ public MyRoomAddStuffResponseDTO addStuff(MyRoomAddStuffRequestDTO myRoomAddStuf
chatRoomJPARepository.save(chatRoom);
MyRoomAddStuffResponseDTO myRoomAddStuffResponseDTO = new MyRoomAddStuffResponseDTO(chatRoom.getId());

// s3에 이미지 저장
List<String> imageUrls = s3Service.uploadFile(multipartFile);

//post 객체 생성
Post post = new Post(member.get(), title, outContent, inContent, 0, 0, currentDateTime, currentDateTime, chatRoom);
postJPARepository.save(post);
Integer postId = postJPARepository.save(post).getId();
System.out.println("postId: "+postId);

// s3에 이미지 저장
List<String> imageUrls = s3Service.uploadFile(multipartFile, String.valueOf(postId));

// url을 DB에 저장
for (String imageUrl : imageUrls) {
Expand Down
16 changes: 15 additions & 1 deletion src/main/java/inandout/backend/service/myroom/S3Service.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,15 @@ public class S3Service {

private final AmazonS3 s3Client;

public List<String> uploadFile(List<MultipartFile> multipartFile) {
public List<String> uploadFile(List<MultipartFile> multipartFile, String postId) {
System.out.println("S3Service/uploadFile");
System.out.println("uploadFile/postId: "+postId);
List<String> fileNameList = new ArrayList<>();

multipartFile.forEach(file -> {
System.out.println(file.toString());
String fileName = createFileName(file.getOriginalFilename()); // 파일 이름 가져옴
fileName = postId+"-"+fileName;
ObjectMetadata objectMetadata = new ObjectMetadata(); // s3에 업로드되는 객체 관련 정보
objectMetadata.setContentLength(file.getSize());
objectMetadata.setContentType(file.getContentType());
Expand All @@ -54,6 +56,18 @@ public List<String> uploadFile(List<MultipartFile> multipartFile) {
return fileNameList;
}


public void deleteFile(Integer postId, List<String> imageUrls){
System.out.println("deleteFile from S3!");

for (String imageUrl : imageUrls) {
System.out.println("삭제: " + imageUrls);
s3Client.deleteObject(bucket, imageUrl);
}


}

// 파일명 중복 방지 (UUID)
private String createFileName(String fileName) {
return UUID.randomUUID().toString().concat(getFileExtension(fileName));
Expand Down
37 changes: 37 additions & 0 deletions src/main/java/inandout/backend/service/post/PostService.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
package inandout.backend.service.post;

import inandout.backend.common.exception.BaseException;
import inandout.backend.common.response.BaseErrorResponse;
import inandout.backend.dto.chat.ChatResponseDTO;
import inandout.backend.dto.myroom.PostResponseDTO;
import inandout.backend.dto.post.UpdateStuffRequestDTO;
import inandout.backend.entity.post.InOut;
import inandout.backend.entity.post.Post;
import inandout.backend.entity.post.PostImage;
import inandout.backend.repository.chat.ChatRepository;
import inandout.backend.repository.post.InOutRepository;
import inandout.backend.repository.post.PostImageJPARepository;
import inandout.backend.repository.post.PostJPARepository;
import inandout.backend.repository.post.PostRepository;
import inandout.backend.service.chat.ChatService;
import inandout.backend.service.myroom.S3Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

Expand All @@ -18,6 +23,8 @@
import java.util.List;
import java.util.Optional;

import static inandout.backend.common.response.status.BaseExceptionResponseStatus.BAD_REQUEST;

@Service
public class PostService {
@Autowired
Expand All @@ -38,6 +45,9 @@ public class PostService {
@Autowired
public InOutRepository inOutRepository;

@Autowired
public S3Service s3Service;

public PostResponseDTO getPost(Integer memberId, Integer postId) {
//postId로 memberId -> memberName
Integer ownerId = chatRepository.getMemberIdByPostId(postId);
Expand Down Expand Up @@ -115,5 +125,32 @@ public Integer plusOutCount(Integer postId) {
}


public void updatePost(Post post, UpdateStuffRequestDTO updateStuffRequestDTO) {

postRepository.updatePost(post.getId(), updateStuffRequestDTO.getTitle(), updateStuffRequestDTO.getInContent(), updateStuffRequestDTO.getOutContent());

}


public void deleteImage(Post post) {
//해당 게시물 기존 이미지 가져오기 & DB에서 삭제
List<String> imageUrls = postImageJPARepository.findUrlByPostId(post.getId());

//DB 에서 삭제
postImageJPARepository.deleteById(post.getId());
System.out.println("postimage 삭제");

//S3에서 삭제
s3Service.deleteFile(post.getId(), imageUrls);


}

public void updatePostImages(Post post, List<String> imageUrls) {
LocalDateTime currentDateTime = LocalDateTime.now(ZoneId.of("Asia/Seoul"));
for (String imageUrl : imageUrls) {
PostImage postImage = new PostImage(post, imageUrl, currentDateTime, currentDateTime);
postImageJPARepository.save(postImage);
}
}
}

0 comments on commit 03ad37a

Please sign in to comment.