공용 responseDto 제네릭

박영준·2023년 7월 26일
0

Java

목록 보기
107/111

1. API 구성

크롤링 해온 데이터를 GET 조회한 결과이다.

body 로 반환된 데이터 형태를 보면
status, message, data 가 있고, data 안에 실제 요청한 데이터가 담겨있다.

2. 코드 구성

1) 공용 responseDto

@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class ApiResponseDto<T> {
    private HttpStatus status;
    private String message;
    private T data;		// 실제 데이터가 담기는 필드
}
  • 제네릭을 사용해서, 타입을 따지지 않고 받을 수 있게 된다.

  • ApiResponseDto 는 전체 프로젝트에서 공통적으로 사용되는 부분이므로, global 패키지 > dto 패키지 안에 생성해두는 것이 좋다.

2) controller

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/articles")
public class ArticleController {

    private final ArticleService articleService;
    private final CrawlingArticle crawlingArticle;
    
	// 크롤링: 전체 기사 조회
    @GetMapping("/crawling")
    public ApiResponseDto<?> saveArticleList() throws IOException {
        return new ApiResponseDto<>(HttpStatus.OK, "OK", crawlingArticle.saveArticleList());
    }
    
    ...
    
}    
  • 반환 타입이 ApiResponseDto 이다.
    • ApiResponseDto 필드 구성과 동일하게, 3번째 값(crawlingArticle.saveArticleList())에 실제 데이터를 담도록 되어있다.
      • crawlingArticle 클래스에 있는 saveArticleList() 메서드로 데이터를 호출한다.

3) ArticleListResponseDto

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class ArticleListResponseDto {
    private Long id;
    private String image;
    private String title;
    private String date;
    private String tag;

    public ArticleListResponseDto(Article article) {
        this.id = article.getId();
        this.image = article.getImage();
        this.title = article.getTitle();
        this.date = article.getDate();
        this.tag = article.getTag();
    }
}

4) service

	// 크롤링: 전체 기사 조회
    public List<ArticleListResponseDto> saveArticleList() throws IOException {
        List<ArticleListResponseDto> articleResponseDtoList = new ArrayList<>();

        for (int i = 1; i <= 10; i++) {
            String Article_URL = "https://www.hani.co.kr/arti/list" + i + ".html";
            articleResponseDtoList.addAll(processUrl(Article_URL));
        }

        return articleResponseDtoList;
    }

(service 로 분류했으나, 실제론 크롤링을 해왔기 때문에 해당 클래스는 CrawlingArticle 이다)

  • ArticleListResponseDto 타입으로 반환하게 된다.

참고: [Java] 자바 제네릭 API Response 활용하기 (Response DTO)

profile
개발자로 거듭나기!

0개의 댓글