코딩과 결혼합니다

230810 - 태그를 누르면 해당 태그의 post가 조회되도록 하기 본문

코딩과 매일매일♥/Seoulvival

230810 - 태그를 누르면 해당 태그의 post가 조회되도록 하기

코딩러버 2023. 8. 10. 19:03
728x90

와이어 프레임

이전에 인기 순위 태그를 불러왔다면 이번에는 그 태그를 클릭하였을 때 해당하는 게시물을 '프론트가 원하는 개수만큼' 조회할 수 있게 할 것이다. 프론트에서 'limit : n' 과 같은 요청을 서버로 보내면 나는 그 n개의 포스트를 response 해주면 된다.


인기 순위 위치태그별 post조회 (limit)

//TagController

@GetMapping("/locationTagName")
public List<LocationPostResponseDto> locationPostResponseDtos(
        @RequestParam int limit,
        @RequestParam String locationTagName
        ){
    return tagService.locationPostResponseDtos(limit, locationTagName);
}

프론트에서 원하는 post의 개수 limit, 그리고 locationTagNaem을 받아와서 service 단으로 넘긴다.

//TagService

//인기 순위 태그별 post 조회
public List<LocationPostResponseDto> locationPostResponseDtos(int limit, String locationTagName) {
    List<LocationPostResponseDto> locationPostResponseDtos = new ArrayList<>();

    LocationTag locationTag = locationTagRepository.findByLocationTag(locationTagName).
            orElseThrow(()-> new IllegalArgumentException("존재하지 않는 태그 입니다."));
    List<Post> postList = postRepository.findAllByLocationTag(Sort.by("createdAt").descending(), locationTag);

    for (int i = 0; i < postList.size(); i++) {
        if (i >= limit) {
            break;
        }
        locationPostResponseDtos.add(new LocationPostResponseDto(postList.get(i)));
    }
    return locationPostResponseDtos;
}
List<LocationPostResponseDto> locationPostResponseDtos = new ArrayList<>(); 
위치 태그별 포스트들을 담을 List를 생성해 준다.
//LocationPostResponseDto

@Getter
public class LocationPostResponseDto {
    private String locationTag;
    private String nickname;
    private String content;
//    private String userImg;

    public LocationPostResponseDto(Post post){
        this.locationTag = post.getLocationTag().getLocationTag();
        this.nickname = post.getUser().getNickname();
        this.content = post.getContent();
//        this.userImg = post.getUser().
    }
}
LocationPostResponseDto 는 로케이션태그, 닉네임, 컨텐트(게시물 내용), 사용자이미지 등의 필드를 가지고 있다. 아직 
User쪽과 Post의 연관관계가 제대로 되지 않았기 때문에 일단 userImg 부분은 주석처리 해주었다.

LocationTag locationTag = locationTagRepository.findByLocationTag(locationTagName).
                orElseThrow(()-> new IllegalArgumentException("존재하지 않는 태그 입니다."));
        List<Post> postList = postRepository.findAllByLocationTag(Sort.by("createdAt").descending(), locationTag);

다시 service로 넘어와서 LocationTag 형식의 객체를 만들어 locationTagRepository에서 클라이언트에서 받아온 locationTagName과 같은 Tag를 찾아서 넣어준다. 없다면 에러메시지를 반환한다.

다음 postRepository 에서 locationTag 태그가 있는 post들을 모두 찾아내 최신순으로 보여주기 위해 정렬한다. 다음 postList에 담아준다.


//LocationTag

@Entity
@Getter
@NoArgsConstructor
public class LocationTag {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "l_tag_id")
    private Long id;

    @Column(nullable = true)
    private String locationTag;

    public LocationTag(String locationTagName) {
        this.locationTag = locationTagName;
    }
}

 for (int i = 0; i < postList.size(); i++) {
            if (i >= limit) {
                break;
            }
            locationPostResponseDtos.add(new LocationPostResponseDto(postList.get(i)));
        }

        return locationPostResponseDtos;
    }

postList를 프론트에서 원하는 개수대로 보내줘야 해서 limit을 건다. 그리고 locationPostResponseDto로 반환해주어야 하므로 locationPostResponseDtos.add(new LocationPostResponseDto(postList.get(i))); 

 

이렇게 인기 순위 위치태그별 post조회도 끝!