Skip to content

Commit

Permalink
Merge branch 'dev' into feat/#5-community-comment
Browse files Browse the repository at this point in the history
  • Loading branch information
jjjjjinseo authored Jul 22, 2024
2 parents 98e0f2b + c44415c commit 764b43d
Show file tree
Hide file tree
Showing 10 changed files with 246 additions and 52 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,5 @@ out/

### VS Code ###
.vscode/

src/main/resources/application.yml
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ dependencies {
implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.2'
runtimeOnly group: 'io.jsonwebtoken', name: 'jjwt-orgjson', version: '0.11.2'
implementation group: 'com.nimbusds', name: 'nimbus-jose-jwt', version: '9.37.2'

//s3
implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,9 @@

@Configuration
@OpenAPIDefinition(
info = @Info(title = "BeginnerFit API 명세",
description = "API 명세",
version = "v1"),
servers = {
@Server(url = "127.0.0.1:8080", description = "Local"),
@Server(url = "3.37.58.77", description = "Server")
}
info = @Info(title = "BeginnerFit WAS",
description = "BeginnerFit API 명세",
version = "v1")
)
public class SwaggerConfig {
@Bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@RestController
@RequiredArgsConstructor
@RequestMapping("/community/posts")
@RequestMapping("/posts")
public class PostController {

private final PostService postService;
Expand All @@ -39,31 +42,29 @@ public ResponseEntity<?> me(HttpServletRequest request) {
return ResponseEntity.ok(postService.me(userId));
}

@GetMapping("/category/{categoryName}")
@GetMapping("/categories/{categoryName}")
@Operation(summary = "카테고리 별 게시글 조회 메소드", description = "카테고리 이름을 통해 카테고리 별로 게시글을 조회합니다.")
public ResponseEntity<?> getPostsByCategoryName(@PathVariable String categoryName) {
return ResponseEntity.ok(postService.getPostsByCategoryName(categoryName));
}

@PostMapping("/create")
@Operation(summary = "게시글 생성 메서드", description = "제목/내용/카테고리이름을 입력받아 게시글을 생성합니다.")
public ResponseEntity<?> update(HttpServletRequest request, @RequestBody PostCreateDto createDto) {
@PostMapping("")
@Operation(summary = "게시글 생성 메서드", description = "제목/내용/카테고리이름/사진(선택)을 입력받아 게시글을 생성합니다.")
public ResponseEntity<?> create(HttpServletRequest request, @RequestPart("createDto") PostCreateDto createDto, @RequestPart(value = "postPicture", required = false) MultipartFile postPicture){
Long userId = jwtUtil.getUserId(jwtUtil.resolveToken(request).substring(7));

return postService.create(userId,createDto);
return postService.create(userId, createDto, postPicture);
}
@PostMapping("/update/{postId}")
@Operation(summary = "사용자 글 수정 메서드", description = "사용자가 마이페이지에서 자신이 작성한 글을 수정합니다.")
ResponseEntity<StateResponse> update(HttpServletRequest request, @PathVariable Long postId, @RequestBody PostUpdateDto postUpdateDto){
@PutMapping("/{postId}")
@Operation(summary = "사용자 글 수정 메서드", description = "사용자가 자신이 작성한 글을 수정합니다.")
ResponseEntity<StateResponse> update(HttpServletRequest request, @PathVariable Long postId, @RequestPart("updateDto") PostUpdateDto updateDto, @RequestPart(value = "postPicture", required = false) MultipartFile postPicture){
Long userId = jwtUtil.getUserId(jwtUtil.resolveToken(request).substring(7));
return postService.update(postId, userId,postUpdateDto);
return postService.update(postId, userId, updateDto ,postPicture);
}
@DeleteMapping("/delete/{postId}")
@DeleteMapping("/{postId}")
@Operation(summary = "게시글 삭제 메서드", description = "사용자가 커뮤니티 글을 삭제하기 위한 메서드입니다.")
ResponseEntity<StateResponse> delete(HttpServletRequest request, @PathVariable Long postId){
Long userId = jwtUtil.getUserId(jwtUtil.resolveToken(request).substring(7));
return postService.delete(postId, userId);
}


}
13 changes: 8 additions & 5 deletions src/main/java/com/example/beginnerfitbe/post/domain/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ public class Post {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

// @Column(nullable = false)
// private String pictureUrl;

@Column(nullable = false)
private String title;

@Column(nullable = false)
private String content;

@Column
private String pictureUrl;

@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
Expand All @@ -47,18 +47,21 @@ public class Post {
private List<Comment> comments;

@Builder
public Post(String title, String content, LocalDateTime createdAt, User user, Category category, List<Comment> comments) {
public Post(String title, String content, String pictureUrl, LocalDateTime createdAt, User user, Category category) {
this.title = title;
this.content = content;
this.pictureUrl = pictureUrl;
this.createdAt = createdAt;
this.category = category;
this.user = user;
this.comments = comments;
}

public void update(String title, String content, Category category) {
this.title=title;
this.content = content;
this.category= category;
}
public void updatePicture(String pictureUrl) {
this.pictureUrl = pictureUrl;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,18 @@ public class PostDto {
private Long id;
private String title;
private String content;
private String pictureUrl;
private LocalDateTime createdAt;

private Long userId;
private String userName;
private String categoryName;

public PostDto(Long id, String title, String content, LocalDateTime createdAt, Long userId, String userName, String categoryName) {
public PostDto(Long id, String title, String content, String pictureUrl, LocalDateTime createdAt, Long userId, String userName, String categoryName) {
this.id = id;
this.title = title;
this.content = content;
this.pictureUrl=pictureUrl;
this.createdAt = createdAt;
this.userId = userId;
this.userName = userName;
Expand All @@ -31,6 +33,7 @@ public static PostDto fromEntity(Post post) {
post.getId(),
post.getTitle(),
post.getContent(),
post.getPictureUrl(),
post.getCreatedAt(),
post.getUser().getId(),
post.getUser().getName(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,19 @@
import com.example.beginnerfitbe.post.dto.PostDto;
import com.example.beginnerfitbe.post.dto.PostUpdateDto;
import com.example.beginnerfitbe.post.repository.PostRepository;
import com.example.beginnerfitbe.s3.util.S3Uploader;
import com.example.beginnerfitbe.user.domain.User;
import com.example.beginnerfitbe.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
Expand All @@ -26,23 +29,36 @@ public class PostService {
private final PostRepository postRepository;
private final UserRepository userRepository;
private final CategoryRepository categoryRepository;
private final S3Uploader s3Uploader;

public ResponseEntity<StateResponse> create(Long userId, PostCreateDto postCreateDto){
User user = userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException("not found user"));
//글 생성
public ResponseEntity<StateResponse> create(Long userId, PostCreateDto postCreateDto, MultipartFile postPicture){
try {
User user = userRepository.findById(userId).orElseThrow(() -> new IllegalArgumentException("not found user"));

Category category = categoryRepository.findByCategoryName(postCreateDto.getCategoryName())
.orElseThrow(() -> new IllegalArgumentException("not found category"));

Category category = categoryRepository.findByCategoryName(postCreateDto.getCategoryName())
.orElseThrow(() -> new IllegalArgumentException("not found category"));
String pictureUrl = null;
if (postPicture != null && !postPicture.isEmpty()) {
pictureUrl = s3Uploader.upload(postPicture, "Post");
}

Post post = Post.builder()
.title(postCreateDto.getTitle())
.content(postCreateDto.getContent())
.createdAt(LocalDateTime.now())
.user(user)
.category(category)
.build();
Post post = Post.builder()
.title(postCreateDto.getTitle())
.content(postCreateDto.getContent())
.pictureUrl(pictureUrl)
.createdAt(LocalDateTime.now())
.user(user)
.category(category)
.build();

postRepository.save(post);
return ResponseEntity.ok(StateResponse.builder().code("SUCCESS").message("글을 성공적으로 생성했습니다.").build());
postRepository.save(post);

return ResponseEntity.ok(StateResponse.builder().code("SUCCESS").message("글을 성공적으로 생성했습니다.").build());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(StateResponse.builder().code("ERROR").message("오류가 발생했습니다: " + e.getMessage()).build());
}
}
//전체 글 조회
public List<PostDto> list(){
Expand Down Expand Up @@ -71,31 +87,58 @@ public List<PostDto> getPostsByCategoryName(String categoryName){
.map(PostDto::fromEntity)
.collect(Collectors.toList());
}
public ResponseEntity<StateResponse> update(Long postId, Long id, PostUpdateDto updateDto){
Post post = postRepository.findById(postId).orElseThrow(() -> new IllegalArgumentException("not found post"));
public ResponseEntity<StateResponse> update(Long postId, Long id, PostUpdateDto updateDto, MultipartFile postPicture) {
try {
Post post = postRepository.findById(postId).orElseThrow(() -> new IllegalArgumentException("not found post"));

Long userId = post.getUser().getId();
if(!userId.equals(id)) throw new IllegalArgumentException("작성자만 글을 수정할 수 있습니다.");
Long userId = post.getUser().getId();
String previousPictureUrl = post.getPictureUrl();

if (!userId.equals(id)) throw new IllegalArgumentException("작성자만 글을 수정할 수 있습니다.");

String title = updateDto.getTitle();
String content = updateDto.getContent();
String categoryName=updateDto.getCategoryName();
String title = updateDto.getTitle();
String content = updateDto.getContent();
String categoryName = updateDto.getCategoryName();

if (title!=null && content!=null && categoryName!=null) {
Category category = categoryRepository.findByCategoryName(categoryName).orElseThrow(() -> new IllegalArgumentException("not found category"));
post.update(title, content, category);
if (title != null && content != null && categoryName != null) {
Category category = categoryRepository.findByCategoryName(categoryName).orElseThrow(() -> new IllegalArgumentException("not found category"));
post.update(title, content, category);
}

if (previousPictureUrl != null) {
s3Uploader.delete("Post",previousPictureUrl);
}
String newPictureUrl=null;
// 사진 수정
if (postPicture != null && !postPicture.isEmpty()) {
if (previousPictureUrl != null) {
s3Uploader.delete("Post",previousPictureUrl);
}
newPictureUrl = s3Uploader.upload(postPicture, "Post");
}
post.updatePicture(newPictureUrl);
postRepository.save(post);
return ResponseEntity.ok(StateResponse.builder().code("SUCCESS").message("게시글을 성공적으로 업데이트했습니다.").build());

} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(StateResponse.builder().code("ERROR").message("오류가 발생했습니다: " + e.getMessage()).build());
}
postRepository.save(post);
return ResponseEntity.ok(StateResponse.builder().code("SUCCESS").message("게시글을 성공적으로 업데이트했습니다.").build());
}

@Transactional
public ResponseEntity<StateResponse> delete(Long postId, Long id){
Post post = postRepository.findById(postId).orElseThrow(() -> new IllegalArgumentException("not found post"));
Long userId = post.getUser().getId();
if(!userId.equals(id)) throw new IllegalArgumentException("작성자만 글을 삭제할 수 있습니다.");

String previousPictureUrl = post.getPictureUrl();
if(previousPictureUrl!=null){
s3Uploader.delete("Post",previousPictureUrl);
}

postRepository.delete(post);
return ResponseEntity.ok(StateResponse.builder().code("SUCCESS").message("글을 성공적으로 삭제했습니다.").build());
}


}
36 changes: 36 additions & 0 deletions src/main/java/com/example/beginnerfitbe/s3/config/S3Config.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.example.beginnerfitbe.s3.config;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class S3Config {

@Value("${BUCKET_ACCESS}")
private String accessKey;

@Value("${BUCKET_SECRET}")
private String secretKey;

@Value("${cloud.aws.region.static}")
private String region;

@Bean
public AmazonS3Client amazonS3Client() {
BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

return (AmazonS3Client) AmazonS3ClientBuilder
.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.build();
}

}
Loading

0 comments on commit 764b43d

Please sign in to comment.