Skip to content

Commit

Permalink
Merge pull request #8 from coke98/feature/#6
Browse files Browse the repository at this point in the history
Feature/#6 Notion Database API 컨트롤러 작성
  • Loading branch information
dmswjdchl authored Sep 22, 2022
2 parents 52b9840 + 0745d84 commit 434b78f
Show file tree
Hide file tree
Showing 11 changed files with 206 additions and 40 deletions.
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.jraf:klibnotion:1.11.0'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: "3.4"
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'mysql:mysql-connector-java'
annotationProcessor 'org.projectlombok:lombok'
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/com/gdscpknu/gdscpknu/GdscpknuApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication
// DB 연결 없이 실행하기 위해 DataSourceAutoConfiguration 제외
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class GdscpknuApplication {

public static void main(String[] args) {
Expand Down
36 changes: 36 additions & 0 deletions src/main/java/com/gdscpknu/gdscpknu/controller/ApiError.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.gdscpknu.gdscpknu.controller;

import lombok.Getter;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.http.HttpStatus;

@Getter
public class ApiError {

private final String MESSAGE = "message";
private final String STATUS = "status";
private final String msg;
private final int status;

public ApiError(String msg, int status) {
this.msg = msg;
this.status = status;
}

public ApiError(String msg, HttpStatus status) {
this(msg, status.value());
}

public ApiError(Throwable throwable, HttpStatus status) {
this(throwable.getMessage(), status.value());
}

@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append(MESSAGE, msg)
.append(STATUS, status)
.toString();
}
}
42 changes: 42 additions & 0 deletions src/main/java/com/gdscpknu/gdscpknu/controller/ApiResponse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.gdscpknu.gdscpknu.controller;

import lombok.Getter;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.http.HttpStatus;

@Getter
public class ApiResponse<T> {

private final boolean success;

private final T response;

private final ApiError error;

public ApiResponse(boolean success, T response, ApiError error) {
this.success = success;
this.response = response;
this.error = error;
}

public static <T> ApiResponse<T> SUCCESS(T response){
return new ApiResponse<>(true, response, null);
}

public static <T> ApiResponse<T> ERROR(String msg, HttpStatus status){
return new ApiResponse<>(false, null, new ApiError(msg, status));
}

public static <T> ApiResponse<T> ERROR(Throwable throwable, HttpStatus status){
return new ApiResponse<>(false, null, new ApiError(throwable, status));
}

public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("success", success)
.append("response", response)
.append("error", error)
.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.gdscpknu.gdscpknu.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import static com.gdscpknu.gdscpknu.controller.ApiResponse.ERROR;


@ControllerAdvice
public class GlobalExceptionHandler {

private final Logger log = LoggerFactory.getLogger(getClass());

private ResponseEntity<ApiResponse<?>> newResponse(Throwable throwable, HttpStatus status) {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
return new ResponseEntity<>(ERROR(throwable, status), headers, status);
}

@ExceptionHandler({
IllegalArgumentException.class,
})
public ResponseEntity<?> handleBadRequestException(Exception e) {
log.debug("Bad request exception occurred: {}", e.getMessage(), e);
return newResponse(e, HttpStatus.BAD_REQUEST);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.gdscpknu.gdscpknu.controller;

import com.gdscpknu.gdscpknu.domain.Member;
import com.gdscpknu.gdscpknu.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
@RequestMapping("/member")
public class MemberController {

private final MemberService memberService;

@Autowired
public MemberController(MemberService memberService) {
this.memberService = memberService;
}


@GetMapping
public ApiResponse<List<Member>> getProfiles() {
return ApiResponse.SUCCESS(memberService.getAllMember());
}
}
7 changes: 3 additions & 4 deletions src/main/java/com/gdscpknu/gdscpknu/domain/Member.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@
@Getter
public class Member {
private String name;
private String email;
private String role;

private String email;
@Builder
public Member(String name, String email, String role) {
public Member(String name, String role, String email) {
this.name = name;
this.email = email;
this.role = role;
this.email = email;
}
}
13 changes: 2 additions & 11 deletions src/main/java/com/gdscpknu/gdscpknu/notion/GdscNotion.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,10 @@
@Component
public class GdscNotion {

@Value("${testNotion.introduce.token}")
@Value("${gdscNotion.introduce.token}")
private String TOKEN;
@Value("${testNotion.introduce.databaseId}")
@Value("${gdscNotion.introduce.databaseId}")
private String DATABASE_ID;
private final BlockingNotionClient client;

public GdscNotion(BlockingNotionClient client) {
this.client = initClient();
}

public BlockingNotionClient initClient() {
NotionClient notionClient = NotionClient.newInstance(
Expand All @@ -30,10 +25,6 @@ public BlockingNotionClient initClient() {
return BlockingNotionClientUtils.asBlockingNotionClient(notionClient);
}

public BlockingNotionClient getClient() {
return client;
}

public String getTOKEN() {
return TOKEN;
}
Expand Down
37 changes: 33 additions & 4 deletions src/main/java/com/gdscpknu/gdscpknu/service/MemberService.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class MemberService {
@Autowired
public MemberService(GdscNotion gdscNotion) {
this.gdscNotion = gdscNotion;
client = gdscNotion.getClient();
client = gdscNotion.initClient();
}

public List<Member> getAllMember() {
Expand All @@ -46,11 +46,13 @@ public List<Member> getAllMember() {
extractName(resultInString);
extractEmail(resultInString);
extractRole(resultInString);
addMember();
addMembers();
sortMembers();

return members;
}


private void getMemberIntroPage() {
memberIntroPage = client.getDatabases().queryDatabase(
gdscNotion.getDATABASE_ID(),
Expand Down Expand Up @@ -84,14 +86,41 @@ private void extractRole(String resultInString) {
}
}

private void addMember() {
private void addMembers() {
for (int i = 0; i < nameList.size(); i++) {
Member member = Member.builder()
.name(nameList.get(i))
.email(emailList.get(i))
.role(roleList.get(i))
.email(emailList.get(i))
.build();
members.add(member);
}
}

private void sortMembers() {
// members를 Lead, Core Member, Member, Senior 순으로 정렬
members.sort((o1, o2) -> {
if (o1.getRole().equals("Lead")) {
return -1;
} else if (o2.getRole().equals("Lead")) {
return 1;
} else if (o1.getRole().equals("Core Member")) {
return -1;
} else if (o2.getRole().equals("Core Member")) {
return 1;
} else if (o1.getRole().equals("Member")) {
return -1;
} else if (o2.getRole().equals("Member")) {
return 1;
} else if (o1.getRole().equals("Senior")) {
return -1;
} else if (o2.getRole().equals("Senior")) {
return 1;
} else {
return 0;
}
});

}

}
43 changes: 25 additions & 18 deletions src/test/java/com/gdscpknu/gdscpknu/notion/NotionApiTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.jraf.klibnotion.model.page.Page;
import org.jraf.klibnotion.model.pagination.Pagination;
import org.jraf.klibnotion.model.pagination.ResultPage;
import org.jraf.klibnotion.model.property.sort.PropertySort;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
Expand Down Expand Up @@ -36,17 +37,16 @@ public void getTable() {
);

//then
// System.out.println("simpleQueryResultPage = " + simpleQueryResultPage.results);
assertThat(database.getTitle().getPlainText()).isEqualTo(notionTable.getTableName());
assertThat(simpleQueryResultPage.results.size()).isEqualTo(notionTable.getMemberNum());
}

@Test
public void getRowByEmail() {
//given
String name = "가나다";
String role = "Core";
String email = "[email protected]";
String name = "남우진";
String role = "Lead";
String email = "[email protected]";

//when
ResultPage<Page> simpleQueryResultPage = client.getDatabases().queryDatabase(
Expand All @@ -73,14 +73,16 @@ public void getRowByEmail() {
@Test
void getPlainTexts() {
//given
String name = "가나다";
String role = "Core";
String email = "[email protected]";
String name = "남우진";
String role = "Lead";
String email = "[email protected]";

// "역할" 기준으로 정렬

ResultPage<Page> simpleQueryResultPage = client.getDatabases().queryDatabase(
notionTable.getDATABASE_ID(),
null,
null,
new PropertySort().ascending("역할"),
new Pagination()
);

Expand All @@ -89,7 +91,9 @@ void getPlainTexts() {
* KlibNotion 라이브러리에서 name, email, role 값을 정규식으로 추출하였음
*/
String resultInString = simpleQueryResultPage.results.toString();
List<String> plainTextList = new ArrayList<>();
List<String> names = new ArrayList<>();
List<String> roles = new ArrayList<>();
List<String> emails = new ArrayList<>();
// 문자열 중 "(plainText=" ~ "," 범위(이름, 이메일) OR " "name=" ~ "," 범위(역할) 문자열을 추출
Pattern namePattern = Pattern.compile("(?<=\\(plainText=)(.*?)(?=,)");
Pattern emailPattern = Pattern.compile("(?<=\\bname=이메일, value=)(.*?)(?=\\))");
Expand All @@ -98,20 +102,23 @@ void getPlainTexts() {
Matcher emailMatcher = emailPattern.matcher(resultInString);
Matcher roleMatcher = rolePattern.matcher(resultInString);
while (nameMatcher.find()) {
plainTextList.add(nameMatcher.group());
}
while (emailMatcher.find()) {
plainTextList.add(emailMatcher.group());
names.add(nameMatcher.group());
}
while (roleMatcher.find()) {
plainTextList.add(roleMatcher.group());
roles.add(roleMatcher.group());
}
while (emailMatcher.find()) {
emails.add(emailMatcher.group());
}


//then
assertThat(plainTextList.size()).isEqualTo(notionTable.getMemberNum() * 3);
assertThat(plainTextList.get(0)).isEqualTo(name);
assertThat(plainTextList.get(3)).isEqualTo(email);
assertThat(plainTextList.get(6)).isEqualTo(role);
assertThat(names.size()).isEqualTo(notionTable.getMemberNum());
assertThat(roles.size()).isEqualTo(notionTable.getMemberNum());
assertThat(emails.size()).isEqualTo(notionTable.getMemberNum());
assertThat(names.get(0)).isEqualTo(name);
assertThat(roles.get(0)).isEqualTo(role);
assertThat(emails.get(0)).isEqualTo(email);
}

}
4 changes: 2 additions & 2 deletions src/test/java/com/gdscpknu/gdscpknu/notion/NotionTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ public class NotionTable {

private final String TOKEN = "";
private final String DATABASE_ID = "";
private final String tableName = "MEMBER PROFILE";
private final int memberNum = 3;
private final String tableName = "멤버 소개";
private final int memberNum = 39;

public BlockingNotionClient initClient() {
NotionClient notionClient = NotionClient.newInstance(
Expand Down

0 comments on commit 434b78f

Please sign in to comment.