DCAMP FRONTEND API 개발 가이드 » 이력 » 버전 29
정성결, 2023-06-19 06:09
1 | 1 | 최시은 | h2. DCAMP FRONTEND API 개발 가이드 |
---|---|---|---|
2 | |||
3 | 3 | 최시은 | 1. SecurityConfig 설정(security/config/SecurityConfig.java) |
4 | 1 | 최시은 | * securityFilterChain 메소드 - 개발 진행할 URL 에 대한 hasAuthority 룰 추가 |
5 | <pre><code class="java"> |
||
6 | http.csrf().disable() |
||
7 | .authorizeHttpRequests((authorize) -> |
||
8 | 2 | 최시은 | authorize |
9 | // hasAuthority 사용: db에 ROLE_ 안붙여도 됨 |
||
10 | .requestMatchers("/projects/**").hasAuthority("ADMIN") // 관리자 : ADMIN | 작업자&검수자 : USER |
||
11 | .anyRequest().authenticated() |
||
12 | 1 | 최시은 | </code></pre> |
13 | 3 | 최시은 | |
14 | 2. Swagger 사용 |
||
15 | * 설정 파일 위치 : common/config/SwaggerConfig.java (이미 설정되어 있으므로 따로 추가사항 없음) |
||
16 | * 접속 URL : http://localhost:18080/swagger-ui/index.html |
||
17 | login-controller 에서 로그인 후, 응답 토큰을 우상단 Authorized 버튼 클릭해서 입력하면 인증 가능 |
||
18 | 4 | 최시은 | |
19 | 8 | 최시은 | 3. Request URL Naming Rule |
20 | 5 | 최시은 | * RESTful API 기반 : https://restfulapi.net/resource-naming/ |
21 | * 1 Depth : 대메뉴(ex, project, user 등등) |
||
22 | <pre>http://api.example.com/user-management/users |
||
23 | http://api.example.com/user-management/users/{id}</pre> |
||
24 | 6 | 최시은 | |
25 | 4. DTO 폴더 |
||
26 | 1 | 최시은 | * 정의 : API 통신용 Request, Response 정의 |
27 | 8 | 최시은 | * Naming Rule : HttpMethod + 대메뉴(복수 or 단수) or 주 사용 테이블 + Req/Res |
28 | <pre> |
||
29 | 예시) |
||
30 | - GetProjectsReq : 프로젝트 목록 조회 요청 |
||
31 | - GetProjectsRes : 프로젝트 목록 조회 응답 |
||
32 | - PostProjectReq : 프로젝트 생성 요청 |
||
33 | - 애매한 경우는 적당히 클래스명만 보고 가늠할 수 있게 지정해주세요 |
||
34 | </pre> |
||
35 | 6 | 최시은 | * 공통 DTO 클래스 |
36 | ** CommonRes : 공통 응답필드(result, message) 정의, 상황에 따른 payload 세팅 가능 |
||
37 | <pre><code class="java"> |
||
38 | @PostMapping |
||
39 | 12 | 최시은 | public ResponseEntity<CommonRes> save(@AuthenticationPrincipal UserDetails userDetails, @RequestBody PostProjectReq req) throws Exception { |
40 | Project project = projectService.createProject(req, userDetails); |
||
41 | CommonRes response = project != null ? new CommonRes() : CommonRes.builder().result(false).message("오류가 발생했습니다.").build(); |
||
42 | return new ResponseEntity<>(response, HttpStatus.OK); |
||
43 | } |
||
44 | 6 | 최시은 | </code></pre> |
45 | 7 | 최시은 | ** CommonListRes : 페이징 목록 조회 시 Response 객체로 사용 |
46 | <pre><code class="java"> |
||
47 | @GetMapping |
||
48 | 12 | 최시은 | public ResponseEntity<CommonListRes<GetProjectsRes>> list(GetProjectsReq req) throws Exception { |
49 | CommonListRes<GetProjectsRes> response = projectService.list(req); |
||
50 | return new ResponseEntity<>(response, HttpStatus.OK); |
||
51 | } |
||
52 | 7 | 최시은 | </code></pre> |
53 | ** CommonSearch : 페이징 목록의 검색 시 Request 객체가 상속 받아 사용(페이징 정보 담김) |
||
54 | <pre><code class="java"> |
||
55 | @AllArgsConstructor |
||
56 | @NoArgsConstructor |
||
57 | @Setter |
||
58 | @Getter |
||
59 | @EqualsAndHashCode(callSuper = false) |
||
60 | public class GetProjectsReq extends CommonSearch { |
||
61 | 1 | 최시은 | |
62 | 7 | 최시은 | private String projectStatusCcd; |
63 | private String searchType; |
||
64 | private String searchWord; |
||
65 | |||
66 | } |
||
67 | </code></pre> |
||
68 | 13 | 최시은 | ** CommonPagination : 페이징 처리를 위해 CommonListRes에서 사용(따로 건드릴 일 없음) |
69 | 9 | 최시은 | |
70 | 5. Entity 폴더 |
||
71 | * 정의 : JPA 에서 사용할 Entity 정의 |
||
72 | |||
73 | 6. DTO 객체와 Entity 객체 분리 사용 |
||
74 | * 이유 : https://wildeveloperetrain.tistory.com/101 |
||
75 | * DTO <-> Entity 는 BeanUtils.copyProperties 사용(필드명 일치시켜야함) |
||
76 | <pre><code class="java"> |
||
77 | public Project createProject(PostProjectReq req, UserDetails userDetails) { |
||
78 | 10 | 최시은 | Project saveProject = new Project(); |
79 | String userId = userDetails.getUsername(); |
||
80 | saveProject.setRegId(userId); |
||
81 | // DTO <-> Entity 변환 |
||
82 | BeanUtils.copyProperties(req, saveProject); |
||
83 | saveProject = projectRepository.save(saveProject); |
||
84 | return saveProject; |
||
85 | } |
||
86 | </code></pre> |
||
87 | |||
88 | 7. 현재 로그인한 아이디 가져오기(regId 에 주로 사용) |
||
89 | 29 | 정성결 | * Spring security 에서 제공하는 @AuthenticationPrincipal 사용해 CustomUserDetails 객체 가져옴 |
90 | 1 | 최시은 | * userDetails.getUsername() 으로 로그인ID 사용 |
91 | 29 | 정성결 | * customUserDetails.getUserSeq() 으로 로그인한 유저의 seq 값 사용 |
92 | 10 | 최시은 | <pre><code class="java"> |
93 | @PostMapping |
||
94 | public ResponseEntity<CommonRes> save(@AuthenticationPrincipal UserDetails userDetails, @RequestBody PostProjectReq req) throws Exception { |
||
95 | 11 | 최시은 | // String userId = userDetails.getUsername(); |
96 | 10 | 최시은 | Project project = projectService.createProject(req, userDetails); |
97 | CommonRes response = project != null ? new CommonRes() : CommonRes.builder().result(false).message("오류가 발생했습니다.").build(); |
||
98 | return new ResponseEntity<>(response, HttpStatus.OK); |
||
99 | } |
||
100 | 1 | 최시은 | </code></pre> |
101 | |||
102 | 23 | 최시은 | 8. 검색 조건에 따른 목록 화면 |
103 | 26 | 노현하 | * 일반적인 case : JPA 에서 제공하는 Pageable 활용 (자세한 내용은 Notice(공지사항) 관련 코드를 참고해주세요.) |
104 | 27 | 노현하 | * 프론트에서 넘겨줘야할 파라미터 목록: pageNumber(현재 페이지 번호, 0 부터 시작), pageSize(페이지 당 행의 개수, default = 10) |
105 | 1 | 최시은 | <pre><code class="java"> |
106 | 26 | 노현하 | // === controller === |
107 | @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) |
||
108 | public ResponseEntity<CommonListRes<GetNoticeRes>> list(GetNoticeReq request, Pageable pageable) { |
||
109 | CommonListRes<GetNoticeRes> response = noticeService.list(request, pageable); |
||
110 | |||
111 | return new ResponseEntity<>(response, HttpStatus.OK); |
||
112 | } |
||
113 | |||
114 | // === service === |
||
115 | public CommonListRes<GetNoticeRes> list(GetNoticeReq req, Pageable pageable) { |
||
116 | Page<Notice> noticePage = noticeRepository.findAllBySearchTypeAndSearchword(req, pageable); |
||
117 | |||
118 | List<GetNoticeRes> getNoticeResList = entityToDto(noticePage.getContent()); |
||
119 | Long totCnt = noticePage.getTotalElements(); |
||
120 | |||
121 | CommonPagination pagination = req.makePaginationInfo(totCnt != null ? totCnt : 0L); |
||
122 | |||
123 | return new CommonListRes<>(getNoticeResList, pagination); |
||
124 | } |
||
125 | |||
126 | 28 | 노현하 | // JpaRepository를 상속받은 인터페이스에서는 querydsl 코드를 작성할 수 없기 때문에 |
127 | 26 | 노현하 | // querydsl용 custom repository 생성 -> 해당 인터페이스를 구현하는 레포지토리 클래스 추가 |
128 | // querydsl용 custom repository는 엔티티 레포지토리에서 상속받아 엔티티 레포지토리로 querydsl 메소드에 접근 |
||
129 | // === repository === |
||
130 | @Repository |
||
131 | public interface NoticeRepository extends JpaRepository<Notice, Integer>, NoticeCustomRepository {} |
||
132 | |||
133 | // === customRepository === |
||
134 | public interface NoticeCustomRepository { |
||
135 | Page<Notice> findAllBySearchTypeAndSearchword(GetNoticeReq req, Pageable pageable); |
||
136 | } |
||
137 | |||
138 | // === customRepositoryImpl === |
||
139 | @Repository |
||
140 | public class NoticeCustomRepositoryImpl implements NoticeCustomRepository { |
||
141 | |||
142 | private final JPAQueryFactory queryFactory; |
||
143 | |||
144 | public NoticeCustomRepositoryImpl(JPAQueryFactory queryFactory) { |
||
145 | this.queryFactory = queryFactory; |
||
146 | } |
||
147 | |||
148 | @Override |
||
149 | public Page<Notice> findAllBySearchTypeAndSearchword(GetNoticeReq req, Pageable pageable) { |
||
150 | List<Notice> notices = queryFactory |
||
151 | .selectFrom(notice) |
||
152 | .where(searchWordEq(req.getSearchType(), req.getSearchWord()), |
||
153 | notice.delYn.eq("N")) |
||
154 | .orderBy(notice.regDt.desc()) |
||
155 | .offset(pageable.getOffset()) |
||
156 | .limit(pageable.getPageSize()) |
||
157 | .fetch(); |
||
158 | |||
159 | Long totCnt = queryFactory |
||
160 | .select(notice.count()) |
||
161 | .from(notice) |
||
162 | .where(searchWordEq(req.getSearchType(), req.getSearchWord()), |
||
163 | notice.delYn.eq("N")) |
||
164 | .fetchOne(); |
||
165 | |||
166 | return new PageImpl<>(notices, pageable, totCnt); |
||
167 | } |
||
168 | |||
169 | 25 | 최시은 | </code></pre> |
170 | * 성능 이슈가 있는 case : Querydsl + 속도 개선을 위한 커버링 인덱스 활용 |
||
171 | 14 | 최시은 | * 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 |
172 | <pre><code class="java"> |
||
173 | public CommonListRes<GetProjectsRes> list(GetProjectsReq req) { |
||
174 | // 1. Querydsl 동적인 조건 검색을 위한 BooleanBuilder & PathBuilder 사용 |
||
175 | BooleanBuilder builder = new BooleanBuilder(); |
||
176 | builder.and(project.useYn.equalsIgnoreCase("Y")); |
||
177 | PathBuilder<Project> pathBuilder = new PathBuilderFactory().create(Project.class); |
||
178 | StringPath path; |
||
179 | |||
180 | // 2. 검색 조건이 담긴 요청 객체의 필드를 순회 하면서 값이 있으면 조건 추가 |
||
181 | BeanWrapper beanWrapper = new BeanWrapperImpl(req); |
||
182 | Field[] fields = GetProjectsReq.class.getDeclaredFields(); |
||
183 | for(Field field : fields){ |
||
184 | if("searchWord".equals(field.getName())) { |
||
185 | continue; |
||
186 | } |
||
187 | if(StringUtils.isNotBlank((String) beanWrapper.getPropertyValue(field.getName()))){ |
||
188 | if("searchType".equals(field.getName())){ |
||
189 | if(StringUtils.isNotBlank(req.getSearchWord())){ |
||
190 | path = pathBuilder.getString(req.getSearchType()); |
||
191 | builder.and(path.contains(req.getSearchWord())); |
||
192 | } |
||
193 | } else { |
||
194 | path = pathBuilder.getString(field.getName()); |
||
195 | builder.and(path.equalsIgnoreCase((String) beanWrapper.getPropertyValue(field.getName()))); |
||
196 | } |
||
197 | } |
||
198 | } |
||
199 | |||
200 | 24 | 최시은 | // 3. 총 건수 카운트 |
201 | Long totCnt = jpaQueryFactory |
||
202 | .select(pathBuilder.count()) |
||
203 | .from(project) |
||
204 | .where(builder) |
||
205 | .fetchOne(); |
||
206 | |||
207 | // 4. 검색 조건이 반영된 ID 리스트 조회 |
||
208 | 14 | 최시은 | List<Integer> projectIds = jpaQueryFactory |
209 | .select(project.projectId) |
||
210 | .from(project) |
||
211 | .where(builder) |
||
212 | 1 | 최시은 | .orderBy(project.regDt.desc()) |
213 | 14 | 최시은 | .limit(req.getPageSize()) |
214 | 24 | 최시은 | .offset(req.getOffset()) |
215 | 14 | 최시은 | .fetch(); |
216 | |||
217 | 24 | 최시은 | // 5. 검색된 ID 기반 전체 필드 조회 (속도 개선을 위한 커버링 인덱스 기법) |
218 | 14 | 최시은 | List<Project> projects = projectIds.isEmpty() |
219 | ? new ArrayList<>() |
||
220 | : jpaQueryFactory |
||
221 | .select(project) |
||
222 | 1 | 최시은 | .from(project) |
223 | .where(project.projectId.in(projectIds)) |
||
224 | 14 | 최시은 | .orderBy(project.regDt.desc()) |
225 | .fetch(); |
||
226 | |||
227 | 24 | 최시은 | // 6. Entity -> DTO |
228 | 14 | 최시은 | List<GetProjectsRes> resultList = new ArrayList<>(); |
229 | projects.forEach(value -> resultList.add(GetProjectsRes.convertToDTO(value))); |
||
230 | |||
231 | 24 | 최시은 | CommonPagination pagination = req.makePaginationInfo(totCnt != null ? totCnt : 0L); |
232 | 14 | 최시은 | return new CommonListRes<>(resultList, pagination); |
233 | 20 | 최시은 | } |
234 | 21 | 최시은 | </code></pre> |