Skip to content

Commit

Permalink
Merge pull request #107 from codestates-seb/feat_be_postimage
Browse files Browse the repository at this point in the history
merge from Feat be postimage to dev_back 230127
  • Loading branch information
Sangyoo authored Jan 26, 2023
2 parents 7283f93 + 7a820f9 commit 0664a53
Show file tree
Hide file tree
Showing 9 changed files with 128 additions and 118 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class HashTag extends Auditable {
@Column(name = "hashtag_content")
private String hashTagContent;

/*@ManyToOne(fetch = FetchType.LAZY)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private Post post;*/
private Post post;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@

import com.main36.pikcha.domain.hashtag.entity.HashTag;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.Optional;

public interface HashTagRepository extends JpaRepository<HashTag, Long> {

Optional<HashTag> findByHashTagContent(String content);

@Query(value = "Select h from HashTag as h where h.hashTagContent = :content and h.post.postId = :postId")
Optional<HashTag> findByPost(String content, long postId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.main36.pikcha.global.exception.BusinessLogicException;
import com.main36.pikcha.global.exception.ExceptionCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
Expand All @@ -14,32 +15,37 @@
@Service
@Transactional
@RequiredArgsConstructor
@Slf4j
public class HashTagService{
private final HashTagRepository hashTagRepository;
public HashTag createHashTag(HashTag hashTag) {
return hashTagRepository.save(hashTag);
}
public HashTag updateHashTag(HashTag hashTag) {
/*public HashTag updateHashTag(HashTag hashTag) {
HashTag findHashTag = findVerifiedHashTag(hashTag.getHashTagContent());
Optional.ofNullable(hashTag.getHashTagContent())
.ifPresent(findHashTag::setHashTagContent);
return hashTagRepository.save(findHashTag);
}*/
public void deleteHashTag(HashTag hashTag, long postId){
HashTag findHashTag = findVerifiedHashTag(hashTag.getHashTagContent(), postId);
log.info("will delete hashTag : {}", findHashTag.getHashTagContent());
hashTagRepository.deleteById(findHashTag.getHashTagId());
}
public void deleteHashTag(HashTag hashTag){
HashTag findHashTag = findVerifiedHashTag(hashTag.getHashTagContent());

hashTagRepository.delete(findHashTag);
}
public void deleteHashTags(List<HashTag> hashTags){
public void deleteHashTags(List<HashTag> hashTags, long postId){
for(HashTag hashTag: hashTags){
HashTag findHashTag = findVerifiedHashTag(hashTag.getHashTagContent());
HashTag findHashTag = findVerifiedHashTag(hashTag.getHashTagContent(), postId);
hashTagRepository.delete(findHashTag);
}
}
public HashTag findVerifiedHashTag(String content){
return hashTagRepository.findByHashTagContent(content)
public HashTag findVerifiedHashTag(String content, long postId){
return hashTagRepository.findByPost(content, postId)
.orElseThrow(()-> new BusinessLogicException(ExceptionCode.HASHTAG_NOT_FOUND));
}

public Optional<HashTag> findHashTag(String content){
return hashTagRepository.findByHashTagContent(content);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@
import com.main36.pikcha.domain.image.entity.PostImage;
import org.springframework.data.jpa.repository.JpaRepository;

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


public interface PostImageRepository extends JpaRepository<PostImage, Long> {

// @Query(value = "select p from PostImage as p where p.Post")
// List<PostImage> findByPostId(long postId);
Optional<PostImage> findByPostImageUrl(String url);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import javax.transaction.Transactional;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

Expand All @@ -25,10 +26,10 @@ public class PostImageService {
public PostImage createPostImage(MultipartFile file) throws IOException {
PostImage postImage = new PostImage();
// 현재 날짜, 시간을 기준으로 생성한 10자리 숫자를 생성
// int dateTimeInteger = (int) (new Date().getTime()/1000);
int dateTimeInteger = (int) (new Date().getTime()/1000);

// 생성된 날짜 + 원래 파일 이름 = 생성되는 파일 이름
String imageFileName = /*dateTimeInteger+*/file.getOriginalFilename();
String imageFileName = dateTimeInteger+file.getOriginalFilename();
String imageUrl = s3Service.upload(file, dirName, imageFileName);

postImage.setPostImageFileName(imageFileName);
Expand Down Expand Up @@ -66,8 +67,23 @@ public void deleteOnlyS3Images(List<PostImage> postImages){
}
}

public void deletePostImagesByUrls(List<String> postImageUrls) {
for(String postImageUrl : postImageUrls) {
PostImage findPostImage = findPostImageByUrl(postImageUrl);
String fileName = findPostImage.getPostImageFileName();
String filePath = dirName + "/" + fileName;
s3Service.delete(filePath);
postImageRepository.delete(findPostImage);
}
}

public PostImage findVerifiedPostImage(long postImageId){
return postImageRepository.findById(postImageId)
.orElseThrow(()-> new BusinessLogicException(ExceptionCode.POST_IMAGE_NOT_FOUND));
}

public PostImage findPostImageByUrl(String url){
return postImageRepository.findByPostImageUrl(url)
.orElseThrow(()->new BusinessLogicException(ExceptionCode.POST_IMAGE_NOT_FOUND));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public class PostController {
@PostMapping("/register/{attraction-id}")
public ResponseEntity<DataResponseDto<?>> registerPost2(Member loginUser,
@PathVariable("attraction-id") @Positive long attractionId,
PostDto.PostDtoFinal postDto) {
PostDto.Post postDto) {
Post post = new Post();

// 포스트 제목 설정
Expand Down Expand Up @@ -109,57 +109,94 @@ public ResponseEntity<DataResponseDto<?>> registerPost2(Member loginUser,
return new ResponseEntity<>(new DataResponseDto<>(response), HttpStatus.CREATED);
}

@PatchMapping("/edit/{post-id}/{member-id}")
public ResponseEntity<DataResponseDto<?>> editPost(@PathVariable("post-id") @Positive long postId,
@PathVariable("member-id") @Positive long memberId,
PostDto.PostDtoFinal postPatchDto) {
Post findPost = postService.findPostNoneSetView(postId);



// 수정할 포스트 캡션, 해시태그, 이미지 전체 삭제
findPost.getPostContents().clear();
findPost.getPostImages().clear();
postImageService.deletePostImages(findPost.getPostImages());
findPost.getHashTags().clear();
hashTagService.deleteHashTags(findPost.getHashTags());

// 포스트 제목 설정
findPost.setPostTitle(postPatchDto.getPostTitle());
@LoginUser
@PatchMapping("/edit/{post-id}")
public ResponseEntity patchPosts(PostDto.Patch patchDto,
Member loginUser,
@PathVariable("post-id") @Positive Long postId){
Post findPost = verifiedById(loginUser.getMemberId(), postId);

// 1. 포스트 제목 변경점 수정 (완료)
if(patchDto.getPostTitle() != null){
if(!patchDto.getPostTitle().equals(findPost.getPostTitle())){
// 받은 제목이 원래 제목과 다르다면 수정
findPost.setPostTitle(patchDto.getPostTitle());
}
}

// 해시태그 데이터 생성 후 추가
if(postPatchDto.getPostHashTags() != null) {
for(String hashtag: postPatchDto.getPostHashTags()) {
HashTag newHashTag = new HashTag();
newHashTag.setHashTagContent(hashtag);
HashTag created = hashTagService.createHashTag(newHashTag);
findPost.getHashTags().add(created);
// 2. 해시태그 변경점 수정
if(patchDto.getPostHashTags() != null) {
// 원래 있던 해시태그 중에
List<HashTag> removed = new ArrayList<>();
for(HashTag hashTag : findPost.getHashTags()){
// patchDto에 이 해시태그가 없다면
if(!patchDto.getPostHashTags().contains(hashTag.getHashTagContent())){
// 해시태그 삭제
removed.add(hashTag);
}
}
findPost.getHashTags().removeAll(removed);
// hashTagService.deleteHashTags(removed, findPost.getPostId());
// patchDto에서
for(String hashTag : patchDto.getPostHashTags()){
// 새로운 해시태그가 있다면
if(hashTagService.findHashTag(hashTag).isEmpty()) {
// 해시태그 생성
HashTag newTag = new HashTag();
newTag.setHashTagContent(hashTag);
// post에 추가
findPost.getHashTags().add(hashTagService.createHashTag(newTag));
// ★ 업데이트를 날려야 하나? ★
}
}
}
// 캡션 추가
if(postPatchDto.getPostContents() != null) {
for(String postContent: postPatchDto.getPostContents()) {
findPost.getPostContents().add(postContent);

// 3. 포스트 캡션 수정
if(patchDto.getPostContents() != null) {
// 원래 있던 캡션 중에
List<String> removed = new ArrayList<>();
for(String content : findPost.getPostContents()){
// patchDto에 이 캡션이 없다면
if(!patchDto.getPostContents().contains(content)){
// content 삭제
removed.add(content);
}
}
findPost.getPostContents().removeAll(removed);
// patchDto에서
for(String content : patchDto.getPostContents()){
// 새로운 content가 있다면
if(!findPost.getPostContents().contains(content)){
// content 추가
findPost.getPostContents().add(content);
}
}
}

// 4. 포스트 이미지 수정 (완료)
if(patchDto.getDeleteUrls() != null) {
// deleteUrls 에 있는 주소로 s3와 데이터베이스에서 삭제
postImageService.deletePostImagesByUrls(patchDto.getDeleteUrls());
}
// 이미지 추가
if(postPatchDto.getPostImageFiles()!= null) {
for(MultipartFile file : postPatchDto.getPostImageFiles()) {

// 5. 포스트 이미지 새로 등록 (완료)
if(patchDto.getPostImageFiles()!= null) {
for(MultipartFile file : patchDto.getPostImageFiles()) {
try{
PostImage postImage = postImageService.createPostImage(file);
findPost.getPostImages().add(postImage);
findPost.getPostImages().add(postImageService.createPostImage(file));
}catch(AmazonServiceException | IOException e) {
e.printStackTrace();
}
}
}
Post createdPost = postService.updatePost(findPost);
PostResponseDto.Detail response = mapper.postToPostDetailResponseDto(createdPost);
response.setIsVoted(postService.isVoted(memberId, postId));
return ResponseEntity.ok(new DataResponseDto<>(response));

// 6. 포스트 업데이트 (완료)
postService.updatePost(findPost);

return new ResponseEntity(HttpStatus.OK);
}


@GetMapping(value = {"/details/{post-id}", "/details/{post-id}/{member-id}"})
public ResponseEntity<DataResponseDto<?>> getPost(@PathVariable("post-id") @Positive long postId,
@PathVariable("member-id") Optional<Long> memberId) {
Expand Down Expand Up @@ -270,21 +307,9 @@ public ResponseEntity<DataResponseDto<?>> votePost(Member loginUser,
}
private Post verifiedById(long memberId, long postId) {
Post post = postService.findPostNoneSetView(postId);

if (!post.getMember().getMemberId().equals(memberId)) {
throw new BusinessLogicException(ExceptionCode.USER_IS_NOT_EQUAL);
}

return post;
}

@PatchMapping
public ResponseEntity patchPosts(HttpServletRequest request){
Set<String> keySet = request.getParameterMap().keySet();
for(String key: keySet) {
log.info(key + ": " + request.getParameter(key));
}

return new ResponseEntity<>(HttpStatus.OK);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,65 +8,22 @@

public class PostDto {
@Data
public static class Post {
@NotBlank(message = "제목을 입력해주세요.")
public static class Post{
private String postTitle;
private String postContent;
private String hashTagContent;
}

@Data
public static class Patch {

private Long postId;
@NotBlank(message = "제목을 입력해주세요.")
private String postTitle;
private String postContent;

//TODO: 정규표현식 적용 -> []
private String hashTagContent;

}

@Data
public static class ImageTest{
private MultipartFile image;
}

@Data
public static class ImageTest2{
private String postTitle;
private String postContent;
private MultipartFile image;
}
@Data
public static class ImageTest3{
private String postContent;
private MultipartFile image;
private List<String> postHashTags;
private List<String> postContents;
private List<MultipartFile> postImageFiles;
}

@Data
public static class ImageTest4{
private String postTitle;
private String postContent;
}

@Data
public static class ImageTest5{
private List<MultipartFile> images;
}
@Data
public static class ImageTest6{
private String postTitle;
private String postContent;
private List<MultipartFile> images;
}
@Data
public static class PostDtoFinal{
public static class Patch{
private String postTitle;
private List<String> postHashTags;
private List<String> postContents;
private List<MultipartFile> postImageFiles;
private List<String> deleteUrls;
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class Post extends Auditable {
private List<String> postContents = new ArrayList<>();


@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE}, orphanRemoval = true)
@JoinColumn(name = "post_id")
private List<HashTag> hashTags = new ArrayList<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING)
public interface PostMapper {

Post postPatchDtoToPost(PostDto.Patch postPatchDto);

default PostResponseDto.Detail postToPostDetailResponseDto(Post post) {

if (post == null) {
Expand Down

0 comments on commit 0664a53

Please sign in to comment.