Project

일반

사용자정보

Actions

DCAMP FRONTEND API 개발 가이드 » 이력 » 개정판 27

« 뒤로 | 개정판 27/31 (비교(diff)) | 다음 »
노현하, 2023-06-08 05:45


DCAMP FRONTEND API 개발 가이드

1. SecurityConfig 설정(security/config/SecurityConfig.java)
  • securityFilterChain 메소드 - 개발 진행할 URL 에 대한 hasAuthority 룰 추가
    http.csrf().disable()
         .authorizeHttpRequests((authorize) ->
               authorize
                   // hasAuthority 사용: db에 ROLE_ 안붙여도 됨
                  .requestMatchers("/projects/**").hasAuthority("ADMIN") // 관리자 : ADMIN | 작업자&검수자 : USER
                  .anyRequest().authenticated()
    
2. Swagger 사용
  • 설정 파일 위치 : common/config/SwaggerConfig.java (이미 설정되어 있으므로 따로 추가사항 없음)
  • 접속 URL : http://localhost:18080/swagger-ui/index.html
    login-controller 에서 로그인 후, 응답 토큰을 우상단 Authorized 버튼 클릭해서 입력하면 인증 가능
3. Request URL Naming Rule
  • RESTful API 기반 : https://restfulapi.net/resource-naming/
  • 1 Depth : 대메뉴(ex, project, user 등등)
    http://api.example.com/user-management/users
    http://api.example.com/user-management/users/{id}
4. DTO 폴더
  • 정의 : API 통신용 Request, Response 정의
  • Naming Rule : HttpMethod + 대메뉴(복수 or 단수) or 주 사용 테이블 + Req/Res
    예시)
    - GetProjectsReq : 프로젝트 목록 조회 요청
    - GetProjectsRes : 프로젝트 목록 조회 응답
    - PostProjectReq : 프로젝트 생성 요청
    - 애매한 경우는 적당히 클래스명만 보고 가늠할 수 있게 지정해주세요
    
  • 공통 DTO 클래스
    • CommonRes : 공통 응답필드(result, message) 정의, 상황에 따른 payload 세팅 가능
      @PostMapping
      public ResponseEntity<CommonRes> save(@AuthenticationPrincipal UserDetails userDetails, @RequestBody PostProjectReq req) throws Exception {
          Project project = projectService.createProject(req, userDetails);
          CommonRes response = project != null ? new CommonRes() : CommonRes.builder().result(false).message("오류가 발생했습니다.").build();
          return new ResponseEntity<>(response, HttpStatus.OK);
      }
      
    • CommonListRes : 페이징 목록 조회 시 Response 객체로 사용
      @GetMapping
      public ResponseEntity<CommonListRes<GetProjectsRes>> list(GetProjectsReq req) throws Exception {
          CommonListRes<GetProjectsRes> response = projectService.list(req);
          return new ResponseEntity<>(response, HttpStatus.OK);
      }
      
    • CommonSearch : 페이징 목록의 검색 시 Request 객체가 상속 받아 사용(페이징 정보 담김)
      @AllArgsConstructor
      @NoArgsConstructor
      @Setter
      @Getter
      @EqualsAndHashCode(callSuper = false)
      public class GetProjectsReq extends CommonSearch {
      
          private String projectStatusCcd;
          private String searchType;
          private String searchWord;
      
      }
      
    • CommonPagination : 페이징 처리를 위해 CommonListRes에서 사용(따로 건드릴 일 없음)
5. Entity 폴더
  • 정의 : JPA 에서 사용할 Entity 정의
6. DTO 객체와 Entity 객체 분리 사용
  • 이유 : https://wildeveloperetrain.tistory.com/101
  • DTO <-> Entity 는 BeanUtils.copyProperties 사용(필드명 일치시켜야함)
    public Project createProject(PostProjectReq req, UserDetails userDetails) {
         Project saveProject = new Project();
         String userId = userDetails.getUsername();
         saveProject.setRegId(userId);
         // DTO <-> Entity 변환
         BeanUtils.copyProperties(req, saveProject);
         saveProject = projectRepository.save(saveProject);
         return saveProject;
    }
    
7. 현재 로그인한 아이디 가져오기(regId 에 주로 사용)
  • Spring security 에서 제공하는 @AuthenticationPrincipal 사용해 UserDetails 객체 가져옴
  • userDetails.getUsername() 으로 로그인ID 사용
    @PostMapping
    public ResponseEntity<CommonRes> save(@AuthenticationPrincipal UserDetails userDetails, @RequestBody PostProjectReq req) throws Exception {
        // String userId = userDetails.getUsername();
        Project project = projectService.createProject(req, userDetails);
        CommonRes response = project != null ? new CommonRes() : CommonRes.builder().result(false).message("오류가 발생했습니다.").build();
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
    
8. 검색 조건에 따른 목록 화면
  • 일반적인 case : JPA 에서 제공하는 Pageable 활용 (자세한 내용은 Notice(공지사항) 관련 코드를 참고해주세요.)
  • 프론트에서 넘겨줘야할 파라미터 목록: pageNumber(현재 페이지 번호, 0 부터 시작), pageSize(페이지 당 행의 개수, default = 10)
    // === controller ===
    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<CommonListRes<GetNoticeRes>> list(GetNoticeReq request, Pageable pageable) {
        CommonListRes<GetNoticeRes> response = noticeService.list(request, pageable);
    
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
    
    // === service ===
    public CommonListRes<GetNoticeRes> list(GetNoticeReq req, Pageable pageable) {
        Page<Notice> noticePage = noticeRepository.findAllBySearchTypeAndSearchword(req, pageable);
    
        List<GetNoticeRes> getNoticeResList = entityToDto(noticePage.getContent());
        Long totCnt = noticePage.getTotalElements();
    
        CommonPagination pagination = req.makePaginationInfo(totCnt != null ? totCnt : 0L);
    
        return new CommonListRes<>(getNoticeResList, pagination);
    }
    
    // JpaRepository를 구현한 인터페이스에서는 querydsl 코드를 작성할 수 없기 때문에
    // querydsl용 custom repository 생성 -> 해당 인터페이스를 구현하는 레포지토리 클래스 추가
    // querydsl용 custom repository는 엔티티 레포지토리에서 상속받아 엔티티 레포지토리로 querydsl 메소드에 접근
    // === repository ===
    @Repository
    public interface NoticeRepository extends JpaRepository<Notice, Integer>, NoticeCustomRepository {}
    
    // === customRepository ===
    public interface NoticeCustomRepository {
        Page<Notice> findAllBySearchTypeAndSearchword(GetNoticeReq req, Pageable pageable);
    }
    
    // === customRepositoryImpl ===
    @Repository
    public class NoticeCustomRepositoryImpl implements NoticeCustomRepository {
    
        private final JPAQueryFactory queryFactory;
    
        public NoticeCustomRepositoryImpl(JPAQueryFactory queryFactory) {
            this.queryFactory = queryFactory;
        }
    
        @Override
        public Page<Notice> findAllBySearchTypeAndSearchword(GetNoticeReq req, Pageable pageable) {
            List<Notice> notices = queryFactory
                    .selectFrom(notice)
                    .where(searchWordEq(req.getSearchType(), req.getSearchWord()),
                           notice.delYn.eq("N"))
                    .orderBy(notice.regDt.desc())
                    .offset(pageable.getOffset())
                    .limit(pageable.getPageSize())
                    .fetch();
    
            Long totCnt = queryFactory
                    .select(notice.count())
                    .from(notice)
                    .where(searchWordEq(req.getSearchType(), req.getSearchWord()),
                           notice.delYn.eq("N"))
                    .fetchOne();
    
            return new PageImpl<>(notices, pageable, totCnt);
        }
    
    
  • 성능 이슈가 있는 case : Querydsl + 속도 개선을 위한 커버링 인덱스 활용
  • 8번 참고 : https://velog.io/@youngerjesus/%EC%9A%B0%EC%95%84%ED%95%9C-%ED%98%95%EC%A0%9C%EB%93%A4%EC%9D%98-Querydsl-%ED%99%9C%EC%9A%A9%EB%B2%95
    public CommonListRes<GetProjectsRes> list(GetProjectsReq req) {
            // 1. Querydsl 동적인 조건 검색을 위한 BooleanBuilder & PathBuilder 사용
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(project.useYn.equalsIgnoreCase("Y"));
            PathBuilder<Project> pathBuilder = new PathBuilderFactory().create(Project.class);
            StringPath path;
    
            // 2. 검색 조건이 담긴 요청 객체의 필드를 순회 하면서 값이 있으면 조건 추가
            BeanWrapper beanWrapper = new BeanWrapperImpl(req);
            Field[] fields = GetProjectsReq.class.getDeclaredFields();
            for(Field field : fields){
                if("searchWord".equals(field.getName())) {
                    continue;
                }
                if(StringUtils.isNotBlank((String) beanWrapper.getPropertyValue(field.getName()))){
                    if("searchType".equals(field.getName())){
                        if(StringUtils.isNotBlank(req.getSearchWord())){
                            path = pathBuilder.getString(req.getSearchType());
                            builder.and(path.contains(req.getSearchWord()));
                        }
                    } else {
                        path = pathBuilder.getString(field.getName());
                        builder.and(path.equalsIgnoreCase((String) beanWrapper.getPropertyValue(field.getName())));
                    }
                }
            }
    
            // 3. 총 건수 카운트
            Long totCnt = jpaQueryFactory
                    .select(pathBuilder.count())
                    .from(project)
                    .where(builder)
                    .fetchOne();
    
            // 4. 검색 조건이 반영된 ID 리스트 조회
            List<Integer> projectIds = jpaQueryFactory
                    .select(project.projectId)
                    .from(project)
                    .where(builder)
                    .orderBy(project.regDt.desc())
                    .limit(req.getPageSize())
                    .offset(req.getOffset())
                    .fetch();
    
            // 5. 검색된 ID 기반 전체 필드 조회 (속도 개선을 위한 커버링 인덱스 기법)
            List<Project> projects = projectIds.isEmpty()
                    ? new ArrayList<>()
                    : jpaQueryFactory
                    .select(project)
                    .from(project)
                    .where(project.projectId.in(projectIds))
                    .orderBy(project.regDt.desc())
                    .fetch();
    
            // 6. Entity -> DTO
            List<GetProjectsRes> resultList = new ArrayList<>();
            projects.forEach(value -> resultList.add(GetProjectsRes.convertToDTO(value)));
    
            CommonPagination pagination = req.makePaginationInfo(totCnt != null ? totCnt : 0L);
            return new CommonListRes<>(resultList, pagination);
        }
    

노현하이(가) 약 2년 전에 변경 · 27 revisions