Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/Leets-Official/X-BE into feat/
Browse files Browse the repository at this point in the history
#28/채팅-비지니스-로직-개선-및-고도화
  • Loading branch information
koreaioi committed Nov 13, 2024
2 parents 2434700 + fab2a6f commit 20f5230
Show file tree
Hide file tree
Showing 23 changed files with 571 additions and 181 deletions.
17 changes: 17 additions & 0 deletions src/main/java/com/leets/X/domain/image/domain/Image.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.leets.X.domain.image.dto.request.ImageDto;
import com.leets.X.domain.post.domain.Post;
import com.leets.X.domain.user.domain.User;
import com.leets.X.global.common.domain.BaseTimeEntity;
import jakarta.persistence.*;
import lombok.*;
Expand All @@ -22,6 +23,10 @@ public class Image extends BaseTimeEntity {

private String url;

@OneToOne
@JoinColumn(name = "user_id")
private User user;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_Id")
private Post post;
Expand All @@ -34,5 +39,17 @@ public static Image from(ImageDto dto, Post post) {
.build();
}

public static Image from(ImageDto dto, User user) {
return Image.builder()
.name(dto.name())
.url(dto.url())
.user(user)
.build();
}

public void update(ImageDto dto) {
this.name = dto.name();
this.url = dto.url();
}

}
16 changes: 16 additions & 0 deletions src/main/java/com/leets/X/domain/image/service/ImageService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.leets.X.domain.image.dto.request.ImageDto;
import com.leets.X.domain.image.repository.ImageRepository;
import com.leets.X.domain.post.domain.Post;
import com.leets.X.domain.user.domain.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -30,4 +31,19 @@ public List<Image> save(List<MultipartFile> file, Post post) throws IOException
return imageRepository.saveAll(imageList);
}

@Transactional
public Image save(MultipartFile image, User user) throws IOException {
ImageDto imageDto = imageUploadService.uploadImage(image);
return imageRepository.save(Image.from(imageDto, user));
}

public ImageDto getImage(MultipartFile image) throws IOException {
return imageUploadService.uploadImage(image);
}

@Transactional
public void delete(Image image) {
imageRepository.delete(image);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,39 @@ public List<ImageDto> uploadImages(List<MultipartFile> files) throws IOException

return images;
}

public ImageDto uploadImage(MultipartFile image) throws IOException {

String originalName = image.getOriginalFilename();
String fileName = generateFileName(originalName);

try {
// PutObjectRequest 생성 및 설정
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(fileName)
.contentType(image.getContentType())
.build();

// S3에 파일 업로드
PutObjectResponse response = s3Client.putObject(
putObjectRequest,
RequestBody.fromInputStream(image.getInputStream(), image.getSize())
);

// 업로드 성공 여부 확인
if (response.sdkHttpResponse().isSuccessful()) {
// 업로드된 파일의 URL을 ImageDto로 추가
return ImageDto.of(originalName, generateFileUrl(fileName));
} else {
throw new S3UploadException();
}
} catch (S3Exception e) {
throw new S3UploadException();
}
}


// S3에 저장된 파일 URL 생성
private String generateFileUrl(String fileName) {
return String.format("https://%s.s3.%s.amazonaws.com/%s", bucketName, region, fileName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.leets.X.domain.post.dto.response.ParentPostResponseDto;
import com.leets.X.domain.post.dto.response.PostResponseDto;
import com.leets.X.domain.post.service.PostService;
import com.leets.X.domain.post.service.RepostService;
import com.leets.X.global.common.response.ResponseDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
Expand All @@ -26,6 +27,7 @@
public class PostController {

private final PostService postService;
private final RepostService repostService;

// 게시물 상세 조회(자식 게시물 까지 함께 조회됨)
@GetMapping("/{id}")
Expand All @@ -37,37 +39,51 @@ public ResponseDto<PostResponseDto> getPost(@PathVariable Long id, @Authenticati

// 모든 부모게시물 조회
@GetMapping("/all")
@Operation(summary = "전체 부모 글 조회")
@Operation(summary = "[Home] 추천 게시글")
public ResponseDto<List<ParentPostResponseDto>> getAllParentPosts(@AuthenticationPrincipal String email) {
List<ParentPostResponseDto> posts = postService.getAllParentPosts(email);
return ResponseDto.response(ResponseMessage.GET_ALL_PARENT_POSTS_SUCCESS.getCode(), ResponseMessage.GET_ALL_PARENT_POSTS_SUCCESS.getMessage(), posts);
}

@GetMapping("/user/{userId}")
@Operation(summary = "[Profile] 유저 게시글 조회")
public ResponseDto<List<ParentPostResponseDto>> getAllUserPosts(@PathVariable Long userId) {
List<ParentPostResponseDto> posts = repostService.getUserFeed(userId);
return ResponseDto.response(ResponseMessage.GET_USER_POST.getCode(), ResponseMessage.GET_USER_POST.getMessage(), posts);
}

@GetMapping("/likes")
@Operation(summary = "좋아요 수로 정렬한 게시물 조회")
public ResponseDto<List<PostResponseDto>> getPostsSortedByLikes(@AuthenticationPrincipal String email) {
List<PostResponseDto> posts = postService.getPostsSortedByLikes(email);
return ResponseDto.response(ResponseMessage.GET_SORTED_BY_LIKES_SUCCESS.getCode(), ResponseMessage.GET_SORTED_BY_LIKES_SUCCESS.getMessage(), posts);
@GetMapping("/following")
@Operation(summary = "[Home] 팔로잉 게시글 조회")
public ResponseDto<List<ParentPostResponseDto>> getAllFollowingPosts(@AuthenticationPrincipal String email) {
List<ParentPostResponseDto> posts = repostService.getFollowingPost(email);
return ResponseDto.response(ResponseMessage.GET_FOLLOWING_POST.getCode(), ResponseMessage.GET_FOLLOWING_POST.getMessage(), posts);
}


@GetMapping("/latest")
@Operation(summary = "최신 게시물 조회")
public ResponseDto<List<ParentPostResponseDto>> getLatestPosts(@AuthenticationPrincipal String email) {
List<ParentPostResponseDto> posts = postService.getLatestParentPosts(email);
return ResponseDto.response(ResponseMessage.GET_LATEST_POST_SUCCESS.getCode(), ResponseMessage.GET_LATEST_POST_SUCCESS.getMessage(), posts);
}
// @GetMapping("/likes")
// @Operation(summary = "좋아요 수로 정렬한 게시물 조회")
// public ResponseDto<List<PostResponseDto>> getPostsSortedByLikes(@AuthenticationPrincipal String email) {
// List<PostResponseDto> posts = postService.getPostsSortedByLikes(email);
// return ResponseDto.response(ResponseMessage.GET_SORTED_BY_LIKES_SUCCESS.getCode(), ResponseMessage.GET_SORTED_BY_LIKES_SUCCESS.getMessage(), posts);
// }


// @GetMapping("/latest")
// @Operation(summary = "최신 게시물 조회")
// public ResponseDto<List<ParentPostResponseDto>> getLatestPosts(@AuthenticationPrincipal String email) {
// List<ParentPostResponseDto> posts = postService.getLatestParentPosts(email);
// return ResponseDto.response(ResponseMessage.GET_LATEST_POST_SUCCESS.getCode(), ResponseMessage.GET_LATEST_POST_SUCCESS.getMessage(), posts);
// }


@PostMapping(value = "/post", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "글 생성")
public ResponseDto<PostResponseDto> createPost(@RequestPart PostRequestDTO postRequestDTO,
public ResponseDto<String> createPost(@RequestPart PostRequestDTO postRequestDTO,
@RequestPart(value = "files", required = false) List<MultipartFile> files,
@AuthenticationPrincipal String email) throws IOException {
// 인증된 사용자의 이메일을 `@AuthenticationPrincipal`을 통해 주입받음
PostResponseDto postResponseDto = postService.createPost(postRequestDTO, files , email);
return ResponseDto.response(ResponseMessage.POST_SUCCESS.getCode(), ResponseMessage.POST_SUCCESS.getMessage(), postResponseDto);
postService.createPost(postRequestDTO, files , email);
return ResponseDto.response(ResponseMessage.POST_SUCCESS.getCode(), ResponseMessage.POST_SUCCESS.getMessage());
}

@PostMapping("/{postId}/like")
Expand All @@ -79,13 +95,13 @@ public ResponseDto<String> addLike(@PathVariable Long postId, @AuthenticationPri

@PostMapping(value = "/{postId}/reply", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "답글 생성")
public ResponseDto<PostResponseDto> createReply(@PathVariable Long postId,
public ResponseDto<String> createReply(@PathVariable Long postId,
@RequestPart PostRequestDTO postRequestDTO,
@RequestPart(value = "files", required = false) List<MultipartFile> files,
@AuthenticationPrincipal String email) throws IOException {
// 답글 생성 서비스 호출 (부모 ID를 직접 전달)
PostResponseDto postResponseDto = postService.createReply(postId, postRequestDTO, files, email);
return ResponseDto.response(ResponseMessage.REPLY_SUCCESS.getCode(), ResponseMessage.REPLY_SUCCESS.getMessage(), postResponseDto);
postService.createReply(postId, postRequestDTO, files, email);
return ResponseDto.response(ResponseMessage.REPLY_SUCCESS.getCode(), ResponseMessage.REPLY_SUCCESS.getMessage());
}


Expand All @@ -104,4 +120,11 @@ public ResponseDto<String> cancelLike(@PathVariable Long postId, @Authentication
return ResponseDto.response(ResponseMessage.LIKE_CANCEL_SUCCESS.getCode(), responseMessage);
}

@PostMapping("/repost/{postId}")
@Operation(summary = "Repost 하기")
public ResponseDto<String> repost(@PathVariable Long postId, @AuthenticationPrincipal String email) {
repostService.rePost(postId, email);
return ResponseDto.response(ResponseMessage.REPOST_SUCCESS.getCode(), ResponseMessage.REPOST_SUCCESS.getMessage());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ public enum ResponseMessage {
POST_DELETED_SUCCESS(200, "게시물이 성공적으로 삭제되었습니다."),
LIKE_CANCEL_SUCCESS(200, "좋아요가 성공적으로 취소되었습니다."),
REPLY_SUCCESS(201, "답글이 생성되었습니다."),
GET_ALL_PARENT_POSTS_SUCCESS(200, "모든 게시글 조회에 성공하였습니다.");
GET_ALL_PARENT_POSTS_SUCCESS(200, "모든 게시글 조회에 성공하였습니다."),
REPOST_SUCCESS(200, "리포스트에 성공했습니다."),
GET_USER_POST(200, "해당 유저의 게시글 조회에 성공했습니다."),
GET_FOLLOWING_POST(200, "팔로우 하는 게시글 조회에 성공했습니다.");

private final int code;
private final String message;
Expand Down
31 changes: 31 additions & 0 deletions src/main/java/com/leets/X/domain/post/domain/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,27 @@ public class Post extends BaseTimeEntity {

private Integer views;

@Enumerated(EnumType.STRING)
private IsDeleted isDeleted;

private LocalDateTime deletedAt;

private Long replyCount;

private Long repostCount;

// 좋아요 수를 관리하기 위한 필드

@Column(name = "like_count")
private Long likeCount = 0L; // 기본값을 0L로 초기화하여 null을 방지

@PrePersist
public void init() {
replyCount = 0L;
repostCount = 0L;
likeCount = 0L;
}

public void updateLikeCount(long newLikeCount) {
this.likeCount = newLikeCount;
}
Expand Down Expand Up @@ -111,5 +123,24 @@ public static Post create(User user, String content, Post parent) {
public void addImage(List<Image> images) {
this.images.addAll(images); // 기존 리스트에 이미지 추가
}

public void increaseReplyCount() {
this.replyCount++;
}

public void decreaseReplyCount() {
if(this.replyCount > 0L) {
this.replyCount--;
}
}

public void increaseRepostCount(){
this.repostCount++;
}
public void decreaseRepostCount() {
if(this.repostCount > 0L) {
this.repostCount--;
}
}
}

33 changes: 33 additions & 0 deletions src/main/java/com/leets/X/domain/post/domain/Repost.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.leets.X.domain.post.domain;

import com.leets.X.domain.user.domain.User;
import jakarta.persistence.*;
import lombok.*;

@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Builder
@Getter
public class Repost {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "repost_id")
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private Post post;

public static Repost of(User user, Post post) {
return Repost.builder()
.user(user)
.post(post)
.build();
}
}
5 changes: 5 additions & 0 deletions src/main/java/com/leets/X/domain/post/domain/enums/Type.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.leets.X.domain.post.domain.enums;

public enum Type {
POST, REPOST
}
Loading

0 comments on commit 20f5230

Please sign in to comment.