Project

일반

사용자정보

DCAMP FRONTEND API 개발 가이드 » 이력 » 버전 30

김지영, 2023-06-20 10:16

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