Skip to content
14 changes: 14 additions & 0 deletions src/main/java/org/battles/battles/exception/ExceptionAdvice.java
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@ protected CommonResult RefreshTokenException(HttpServletRequest request, Excepti
return responseService.getFailResultWithMsg("잘못된 Refresh 토큰입니다. 다시 입력해주세요.");
}


@ExceptionHandler(CSchoolNotFoundException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult SchoolNotFoundException(HttpServletRequest request, Exception e) {
return responseService.getFailResultWithMsg("해당 학교가 존재하지 않거나 잘못된 학교입니다.");
}
@ExceptionHandler(CCategoryExistedException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult CategoryExistedException(HttpServletRequest request, Exception e) {
Expand Down Expand Up @@ -145,5 +151,13 @@ protected CommonResult BattleExistedException(HttpServletRequest request, Except
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult BattleNotFoundException(HttpServletRequest request, Exception e) {
return responseService.getFailResultWithMsg("해당 경기가 존재하지 않습니다.");

}

@ExceptionHandler(CPostNotFoundException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
protected CommonResult PostNotFoundException(HttpServletRequest request, Exception e) {
return responseService.getFailResultWithMsg("해당 게시글이 존재하지 않습니다.");

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package org.battles.battles.exception.exception;

public class CPostNotFoundException extends RuntimeException {

public CPostNotFoundException(String msg, Throwable t) {
super(msg, t);
}

public CPostNotFoundException(String msg) {
super(msg);
}

public CPostNotFoundException() {
super();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package org.battles.battles.exception.exception;

public class CSchoolNotFoundException extends RuntimeException{

public CSchoolNotFoundException(String msg, Throwable t) {
super(msg, t);
}

public CSchoolNotFoundException(String msg) {
super(msg);
}

public CSchoolNotFoundException() {
super();
}
}
59 changes: 59 additions & 0 deletions src/main/java/org/battles/battles/post/Dto/PostsResponseDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package org.battles.battles.post.Dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.battles.battles.battle.Battle;
import org.battles.battles.battle.category.Category;
import org.battles.battles.common.Status;
import org.battles.battles.post.Post;
import org.battles.battles.post.PostType;
import org.battles.battles.school.School;
import org.battles.battles.user.User;

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

@Builder
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class PostsResponseDto {
private Long postId;

private Long userId;

private String nickName;

private Long schoolId;

private String schoolName;

private String title;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드 좋습니다!! 다만 api문서를 그렇게 작성했던 것 같긴 한데 순간 response로 모두 보내줘야 할까 싶은데 .. 어떻게 생각하세요? 모두 보내줘야겠다 싶으시면 이부분은 수정안하셔도 됩니다!


private String content;

private PostType postType;

private Status status;

private LocalDateTime createdAt;

private LocalDateTime modifiedAt;

public PostsResponseDto(Post post) {
this.postId = post.getPostId();
this.userId = post.getUser().getUserId();
this.nickName = post.getUser().getNickName();
this.schoolId = post.getUser().getSchool().getSchoolId();
this.schoolName = post.getUser().getSchool().getSchoolName();
this.title = post.getTitle();
this.content = post.getContent();
this.postType = post.getPostType();
this.status = post.getStatus();
this.createdAt = post.getCreatedAt();
this.modifiedAt = post.getModifiedAt();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package org.battles.battles.post.Dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.battles.battles.common.Status;
import org.battles.battles.post.Post;
import org.battles.battles.post.PostType;
import org.battles.battles.school.School;
import org.battles.battles.user.User;

import java.util.Optional;

@Builder
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class PostsSaveRequestDto {
private String title;
private String content;


}
21 changes: 12 additions & 9 deletions src/main/java/org/battles/battles/post/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import lombok.NoArgsConstructor;
import org.battles.battles.common.Status;
import org.battles.battles.common.TimeStamped;
import org.battles.battles.school.School;
import org.battles.battles.user.User;

import javax.persistence.*;

Expand All @@ -15,20 +17,21 @@
@AllArgsConstructor
@Entity
@Table(name = "Post_Table")

public class Post extends TimeStamped {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long postId;

// fix me = fk mapping 필요
@Column(nullable = false)
private Long userId;
// fix me = fk mapping 필요
@ManyToOne
@JoinColumn(name = "userId", nullable = true)
private User user;

// fix me = fk mapping 필요
@Column(nullable = true)
private Long schoolId;
@ManyToOne
@JoinColumn(name = "schoolId", nullable = true)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

매핑 잘 하셨는데 지금 언뜻 서치해보니까 fk null이면 에러가 난다는.... 설계를 다시 해봐야겠네요 ㅠㅠㅠ

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fk null 허용되지 않나요? JPA라서 그런가요??

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jpa라서 그런건 아니고.. 아 fk가 pk 동시일때 null허용은 안되는구나 원래 db상으로는... 음 고민이되네요 null이 좋은 방식은 아닌 것 같긴 해요 ㅠㅠ 고민고민

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

음 더 알아보겠습니다. @yejipractice

Copy link
Copy Markdown
Member Author

@imchanyang imchanyang Aug 28, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Post의 schooId 컬럼에 값을 전부(전체/학교) 다 넣어준다.
  2. Post의 schoolId 컬럼을 빼고 필요할 때 마다 User를 통해 조회한다.

정도 고민이 있는 것 같습니다.

개발하고 있는데 schoolID가 NULL이 되면 코드가 많아지기도 했습니다..

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. 둘의 테이블을 나눠버린다?

private School school;

@Column(nullable = false)
private String title;
Expand All @@ -45,9 +48,9 @@ public class Post extends TimeStamped {
private Status status;

@Builder
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

빌더는 빼주세요~!

public Post(Long userId, Long schoolId, String title, String content, PostType postType, Status status) {
this.userId = userId;
this.schoolId = schoolId;
public Post(User user, School school, String title, String content, PostType postType, Status status) {
this.user = user;
this.school = school;
this.title = title;
this.content = content;
this.postType = postType;
Expand Down
77 changes: 76 additions & 1 deletion src/main/java/org/battles/battles/post/PostController.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,79 @@
package org.battles.battles.post;

public class PostController {
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.battles.battles.post.Dto.PostsSaveRequestDto;
import org.battles.battles.response.CommonResult;
import org.battles.battles.response.ResponseService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.Authentication;

@Api(tags = {"6. 게시판 컨트롤러"})
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/post")
@Slf4j
public class PostController{
private final ResponseService responseService;

private final PostService postService;
@ApiImplicitParams({
@ApiImplicitParam(name = "AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "전체 게시글 작성", notes = "회원정보와 제목, 내용을 입력하여 전체 게시글을 작성한다.")
@PostMapping("/entire")
public CommonResult saveEntire(@RequestBody PostsSaveRequestDto requestDto) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getName();

return responseService.getSingleResult(postService.saveEntire(email, requestDto));
}

@ApiImplicitParams({
@ApiImplicitParam(name = "AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
})
@ApiOperation(value = "학교 게시글 작성", notes = "회원정보와 제목, 내용을 입력하여 학교 게시글을 작성한다.")
@PostMapping("/{schoolId}")
public CommonResult saveSchool(@RequestBody PostsSaveRequestDto requestDto, @PathVariable Long schoolId) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String email = authentication.getName();

return responseService.getSingleResult(postService.saveSchool(email, requestDto, schoolId));
}
@ApiOperation(value = "게시글 단건 조회", notes = "게시글 단건을 조회한다.")
@GetMapping("/{postId}")
public CommonResult getPostById(@PathVariable Long postId) {

return responseService.getSingleResult(postService.getPostById(postId));
}



@ApiOperation(value = "전체 게시글 조회", notes = "전체 게시글을 조회한다.")
@GetMapping("/entire")
public CommonResult getEntirePosts() {

return responseService.getListResult(postService.getPostAllEntire());
}

@ApiOperation(value = "학교별 게시글 조회", notes = "학교 게시글을 조회한다.")
@GetMapping("/school/{schoolId}")
public CommonResult getSchoolPosts(@PathVariable Long schoolId) {

return responseService.getListResult(postService.getPostAllSchool(schoolId));
}


@ApiOperation(value = "모든 게시글 조회", notes = "모든 게시글을 조회한다.")
@GetMapping("/all")
public CommonResult getAllPosts() {

return responseService.getListResult(postService.getPostAll());
}

}
5 changes: 5 additions & 0 deletions src/main/java/org/battles/battles/post/PostRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,10 @@

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface PostRepository extends JpaRepository<Post, Long> {

List<Post> findAllByPostType(PostType postType);

}
Loading