Skip to content

Commit

Permalink
변수명 수정 및 service, controller 전반적 로직 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
3un0ia committed Mar 16, 2024
1 parent 32d24b4 commit eb12cba
Show file tree
Hide file tree
Showing 9 changed files with 188 additions and 157 deletions.
6 changes: 5 additions & 1 deletion JWT/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ dependencies {

implementation 'mysql:mysql-connector-java:8.0.33'
runtimeOnly 'mysql:mysql-connector-java'
runtimeOnly 'com.h2database:h2'

compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
Expand All @@ -42,8 +43,11 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.2'

// // Spring Security

testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation ('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}

tasks.named('test') {
Expand Down
81 changes: 41 additions & 40 deletions JWT/src/main/java/JWTLogIn/JWT/post/controller/PostController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@

import JWTLogIn.JWT.post.dto.PostDto;
import JWTLogIn.JWT.post.entity.PostEntity;
import JWTLogIn.JWT.post.entity.Type;
import JWTLogIn.JWT.post.repository.PostRepository;
import JWTLogIn.JWT.post.service.PostService;
import JWTLogIn.JWT.user.entity.UserEntity;
import JWTLogIn.JWT.user.repository.UserRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -36,41 +39,35 @@ public class PostController {
* */
private final PostService postService;
private final PostRepository postRepository;
private final UserRepository userRepository;
// private final UserRepository userRepository;

@CrossOrigin
@GetMapping("/info/notice") // 공지글 가져오기 - GET, /tgwing.kr/info/notice
public ResponseEntity<List<PostDto>> getAllPosts() {
System.out.println("-- Retrieve All of Posts --");

// post.isAdmin() = 1이면 관리자가 올린 글, 아니면 일반인이 올린 글 ( != 공지)
// DB에서 모든 유저 가져와서 각 유저마다 가지고 있는 post list를 가져옴
// one user의 post list에서 isAdmin이 1인 post를 모두 보여주기
// postEntity.type = NOT, GAL --> NOT이면 공지, GAL이면 갤러리
// DB에서 가져온 모든 POST 중에서 type = NOT인 게시글을 모두 가져옴
List<PostDto> result = new ArrayList<>();

List<UserEntity> allUser = userRepository.findAll();

List<PostDto> allPostDto = new ArrayList<>();

// 모든 유저에 대해서 : 모든 글에 대한 정보 모아서, list에 추가
for (UserEntity user : allUser) {
List<PostDto> userPostDtos = postService.getPostsByUserId(user.getId());
allPostDto.addAll(userPostDtos);
List<PostEntity> allPosts = postRepository.findAll();
for (PostEntity post : allPosts) {
if (post.getType() == Type.NOT) {
result.add(toDto(post));
}
}

// 모든 유저에 대해서 : 모든 글에 대해서 list에 추가
return new ResponseEntity<>(allPostDto, HttpStatus.OK);
return new ResponseEntity<>(result, HttpStatus.OK);
}
@CrossOrigin

@GetMapping("/info/notice/{postId}") // 특정 공지글 가져오기 - GET, /tgwing.kr/info/notice/{id}
public ResponseEntity<PostDto> getPost(@PathVariable("postId") Long postId) {
System.out.println("-- Retreive Specific Post by Id --");
// 특정 게시글 id에 대한 post 정보를 모아 반환 (id, title, description, writtenDate, ?조회수?

PostDto post = postService.getPost(postId);
return ResponseEntity.ok(post);

}
@CrossOrigin

@GetMapping("/notice/search") // 공지 내용 검색 - GET, /tgwing.kr/notice/search?text={search}
public ResponseEntity<List<PostDto>> searchPost(@RequestParam String text)
{
Expand All @@ -81,56 +78,60 @@ public ResponseEntity<List<PostDto>> searchPost(@RequestParam String text)
List<PostDto> postDtos = postService.searchPosts(text);
return ResponseEntity.ok(postDtos);
}
@CrossOrigin

@PostMapping("/notice/post/{userId}") // 공지 작성 - POST, /tgwing.kr/notice/post
public ResponseEntity<PostDto> post(@RequestBody PostDto postDto,
public ResponseEntity<PostDto> post(@RequestBody PostDto requestDto,
@PathVariable("userId") Long userId)
{
System.out.println("-- Post new post --");
System.out.println("postDto = " + postDto);
// 가져오는 값 : 제목, 내용, 사진url
System.out.println("Request Dto = " + requestDto);
// RequestDTO : title, content, thumbnail(선택)
// userId : 해당 URL을 요청한 유저의 Id

// dto 가져온 값을 엔티티로 바꾸고 DB에 save
// 다시 꺼내와서 완성된 객체의 구성요소(id, title, description, writtenDate ...)

PostEntity post = postService.createPost(postDto, userId);
PostDto returnDto = toDto(post);
return ResponseEntity.ok(returnDto);
// 유저의 level 확인 필요 - level = MANAGER인 경우에만 작성가능
// 로그인 되어있지 않은 경우 NORMAL, 로그인 된 경우 MEMBER, 관리자인 경우 MANAGER

PostDto responseDto = postService.createPost(requestDto, userId);
return ResponseEntity.ok(responseDto);
}
@CrossOrigin
@PutMapping("/notice/put/{id}") // 공지 수정 - PUT, /tgwing.kr/notice/put/{id}
public ResponseEntity<PostDto> modify(@RequestBody PostDto postDto,
// @CrossOrigin
@PatchMapping ("/notice/put/{id}") // 공지 수정 - PUT, /tgwing.kr/notice/put/{id}
public ResponseEntity<PostDto> modify(@RequestBody PostDto requestDto,
@RequestParam Long userId,
@PathVariable("id") Long id)
{
System.out.println("-- Modify (title + description) of post --");
System.out.println("-- Modify (title + content) of post --");
// repository에 대해서 해당 id를 가진 엔티티를 가져오고,
// 그 엔티티의 내용을 dto 내용으로 수정 및 다시 repository에 저장한다

System.out.println("postDto = " + postDto);
PostEntity updatedEntity = postService.updatePost(postDto, id);
PostDto updatedDto = toDto(updatedEntity);
System.out.println("Request Dto = " + requestDto);

return ResponseEntity.ok(updatedDto);
PostDto responseDto = postService.updatePost(requestDto, userId, id);

return ResponseEntity.ok(responseDto);
}

@CrossOrigin
@DeleteMapping("/notice/delete/{id}") // 공지 삭제 - DELETE, /tgwing.kr/notice/delete/{id}
public ResponseEntity<Void> delete(@PathVariable("id") Long id)
public ResponseEntity<Void> delete(@PathVariable("id") Long id,
@RequestParam Long userId)
{
System.out.println("-- Delete Specific Post --");
// 아이디에 해당하는 글 객체를 그냥 삭제 -> 응답
postService.deletePost(id);
postService.deletePost(userId, id);
return ResponseEntity.noContent().build();
}


@CrossOrigin
@GetMapping("/notice")
@Transactional
public ResponseEntity<Page> getPostsInPage(@RequestParam int page,
@RequestParam(required = false, defaultValue = "15") int size) {
@RequestParam(required = false) int size,
@PageableDefault(size = 15) Pageable pageable) {
System.out.println("-- Get Posts in Page --");
// 첫 번째 페이지 page = 0이므로, page-1로 전달 -> 1부터 요청할 수 있도록
Page<PostDto> postsInPage = postService.findPostsInPage(page-1, size);
Page<PostDto> postsInPage = postService.findPostsInPage(page-1, size, pageable);

return ResponseEntity.ok(postsInPage);
}
Expand Down
22 changes: 16 additions & 6 deletions JWT/src/main/java/JWTLogIn/JWT/post/dto/PostDto.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,32 @@
package JWTLogIn.JWT.post.dto;

import JWTLogIn.JWT.post.entity.PostEntity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

@Data
@AllArgsConstructor
@Builder
public class PostDto {
private String author;
private Long writer;
private String title;
private String description;
private String picture;
private String content;
private String thumbnail;

public static PostEntity toEntity(PostDto postDto) {
return PostEntity.builder()
.author(postDto.author)
.writer(postDto.writer)
.title(postDto.title)
.description(postDto.description)
.picture(postDto.picture).build();
.content(postDto.content)
.thumbnail(postDto.thumbnail).build();
}

public static PostEntity toEntityWithId (PostDto postDto, Long writerId) {
return PostEntity.builder()
.writer(writerId)
.title(postDto.title)
.content(postDto.content)
.thumbnail(postDto.thumbnail).build();
}
}
43 changes: 19 additions & 24 deletions JWT/src/main/java/JWTLogIn/JWT/post/entity/PostEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;

@Entity
@Getter
Expand All @@ -19,37 +17,34 @@ public class PostEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String author;
@Column(name = "written_date")
private LocalDateTime writtenDate;
@JoinColumn(referencedColumnName = "id", table = "user")
private Long writer;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String description;
private String picture;
@Column(name = "recommand_num")
private int recommandNum;
private String content;
private String thumbnail;
private Type type;


// 연관매핑: 다대일
// 참조하는(외래키를 가진) 엔티티에서 사용
// FetchType (EAGER: 객체가 사용되지 않아도 조회 & 조회 시 연관 엔티티 한 번에 조회
// LAZY: 엔티티 사용 시점에 조회)
// @ManyToOne
// @JoinColumn(name="student_id", referencedColumnName = "student_id")
// private UserEntity user;
@JsonIgnore
@ManyToOne
@JoinColumn(referencedColumnName = "student_id")
private UserEntity user;

public static PostDto toDto(PostEntity postEntity) {
return PostDto.builder()
.author(postEntity.author)
.writer(postEntity.writer)
.title(postEntity.title)
.description(postEntity.description)
.picture(postEntity.picture).build();
.content(postEntity.content)
.thumbnail(postEntity.thumbnail).build();
}

public void updateContent(PostDto postDto) {
this.title = postDto.getTitle();
this.content = postDto.getContent();
this.thumbnail = postDto.getThumbnail();
}
//
// public void updateContent(PostDto postDto) {
// this.author = this.user.getName();
// this.title = postDto.getTitle();
// this.description = postDto.getDescription();
// this.picture = postDto.getPicture();
// }
}
5 changes: 5 additions & 0 deletions JWT/src/main/java/JWTLogIn/JWT/post/entity/Type.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package JWTLogIn.JWT.post.entity;

public enum Type {
NOT, GAL
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,17 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

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


@Repository
public interface PostRepository extends JpaRepository<PostEntity, Long> {
Optional<PostEntity> findById(Long id);

@Override
<S extends PostEntity> S save(S entity);

// List<PostEntity> findByTitleContains(String search);
List<PostEntity> findByDescriptionContains(String search);
List<PostEntity> findByContentContains(String search);
Page<PostEntity> findAllByOrderByIdDesc(Pageable pageable);
}
Loading

0 comments on commit eb12cba

Please sign in to comment.