모집글을 등록할 수 있는 api를 구현해본다.
모집글에는 기본적인 title, content , category, (등록하는 사용자의) userEmail (➡️ 이건 토큰을 이용할 수 있게 되면 변경할 예정이다.) 이 필요하다.
추가적으로 모집글 등록 시에 함께 생성해야 할 Match 객체의 필드들이 필요하고 성별, 나이대, 난이도 등을 표기할 수 있는 Tag 객체가 들어간다.
(✅ Match : 경기 인원 수, 경기 장소, 경기 날짜가 들어간다.)

나름대로 체계적으로 정리하려고 노력 중인데 잘하고 있나 모르겠다..~
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class AddPostRequest {
    private String title;
    private String content;
    private String category;
    private String userEmail;
    private Match match;
    private Tag tag;
    public Post postToEntity(Tag tag, Match match, User user) {
       return Post.builder()
               .category(category)
               .tag(tag)
               .match(match)
               .user(user)
               .title(title)
               .content(content)
               .build();
    }
    public Match matchToEntity(User user) {
        return Match.builder()
                .user(user)
                .category(category)
                .headCnt(match.getHeadCnt())
                .place(match.getPlace())
                .matchDate(match.getMatchDate())
                .build();
    }
    public Tag tagToEntity() {
        return Tag.builder()
                .ageType(tag.getAgeType())
                .genderType(tag.getGenderType())
                .levelType(tag.getLevelType())
                .build();
    }
} 처음에는 무슨 생각이었는지 그냥 Tag, Match 객체의 필드들도 다 따로따로 받아서 이것들을 다시 각각의 dto 로 만들고 이것을 엔티티로 만들어서 모집글 저장 시에 함께 추가하여 저장하는 굉장히 복잡한 방식으로 구현을 했다. 제대로 돌아가긴 하는데 아무래도 너무 복잡해보였고 역시나 request body 에 객체 자체를 받아도 되는거였다..
이 객체를 엔티티로 변환하는 메서드는 matchToEntity(), tagToEntity() 로 만들어서 postToEntity()와 함께 dto 자바 파일에 두었다.
    public Long save(AddPostRequest dto) {
        User user = userRepository.findByEmail(dto.getUserEmail()).orElseThrow(null);
        Tag tag = dto.tagToEntity();
        Tag savedTag = tagRepository.save(tag);
        Match match = dto.matchToEntity(user);
        Match savedMatch = matchRepository.save(match);
        Post post = dto.postToEntity(savedTag,savedMatch,user);
        postRepository.save(post);
        return post.getPostId();
    }addPostRequest dto 에 있는 엔티티 변환 메서드들을 여기에서 모두 사용한다. user 은 request body에 담겨오는 email을 통해 찾은 객체이다. tag, match 는 모두 __ToEntity() 을 이용해 객체에서 엔티티로 변환한다.
✅ 여기서 바로 post에 담으면 안되고 저장하고 리턴되는 객체를 담아야 오류가 나지 않는다.
    @PostMapping("/api/post")
    public ResponseEntity<Map<String,Long>> addPost(@RequestBody AddPostRequest request) {
        Long savedPost = postService.save(request);
        Map<String,Long> response = new HashMap<>();
        response.put("postId",savedPost);
        return ResponseEntity.status(HttpStatus.CREATED).body(response);
    }모집글 등록이 완료되면 response로 모집글 전체 내용보단 그냥 모집글 id만 보내주면 될 것 같은데...? 이것도 dto로 만들어야 돼? 라고 생각했는데 역시 그럴리가 없었다. Map<>을 이용해 "postId" 에 저장된 postId를 담아주고 ResponseEntity body에 쏙 넣어준다!

등록 확인!

조회 확인!