Compare commits
2 Commits
74f8b65327
...
2ead0f0f12
Author | SHA1 | Date | |
---|---|---|---|
2ead0f0f12 | |||
e0e868a282 |
53
README.md
53
README.md
@@ -8,6 +8,7 @@
|
|||||||
- **Security**: Spring Security + JWT
|
- **Security**: Spring Security + JWT
|
||||||
- **Build Tool**: Gradle
|
- **Build Tool**: Gradle
|
||||||
- **Container**: Docker + Kubernetes
|
- **Container**: Docker + Kubernetes
|
||||||
|
- **API Documentation**: Swagger (SpringDoc OpenAPI)
|
||||||
|
|
||||||
## 개발 가이드
|
## 개발 가이드
|
||||||
|
|
||||||
@@ -31,7 +32,30 @@ src/main/java/com/bio/bio_backend/
|
|||||||
└── BioBackendApplication.java
|
└── BioBackendApplication.java
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 트랜잭션 관리
|
### 2. API 문서화 (Swagger)
|
||||||
|
|
||||||
|
#### Swagger UI 접속
|
||||||
|
|
||||||
|
- **URL**: `http://localhost:8080/service/swagger-ui.html`
|
||||||
|
- **API Docs**: `http://localhost:8080/service/api-docs`
|
||||||
|
|
||||||
|
#### 주요 어노테이션
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Tag(name = "Member", description = "회원 관리 API")
|
||||||
|
@Operation(summary = "회원 가입", description = "새로운 회원을 등록합니다.")
|
||||||
|
@ApiResponses(value = {
|
||||||
|
@ApiResponse(responseCode = "201", description = "회원 가입 성공"),
|
||||||
|
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터")
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 설정 파일
|
||||||
|
|
||||||
|
- **SwaggerConfig.java**: OpenAPI 기본 정보 설정
|
||||||
|
- **application.properties**: Swagger UI 커스터마이징
|
||||||
|
|
||||||
|
### 3. 트랜잭션 관리
|
||||||
|
|
||||||
#### 기본 설정
|
#### 기본 설정
|
||||||
|
|
||||||
@@ -54,3 +78,30 @@ public class MemberServiceImpl {
|
|||||||
- **클래스 레벨**: `@Transactional(readOnly = true)` 기본 설정
|
- **클래스 레벨**: `@Transactional(readOnly = true)` 기본 설정
|
||||||
- **메서드별**: 데이터 수정 시에만 `@Transactional` 개별 적용
|
- **메서드별**: 데이터 수정 시에만 `@Transactional` 개별 적용
|
||||||
- **설정**: `spring.jpa.open-in-view=false` (성능 최적화)
|
- **설정**: `spring.jpa.open-in-view=false` (성능 최적화)
|
||||||
|
|
||||||
|
### 4. 오류 등록 및 사용
|
||||||
|
|
||||||
|
#### 오류 코드 등록
|
||||||
|
|
||||||
|
```java
|
||||||
|
// ApiResponseCode.java
|
||||||
|
public enum ApiResponseCode {
|
||||||
|
USER_ID_DUPLICATE("400", "이미 존재하는 사용자 ID입니다."),
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 오류 사용 방법
|
||||||
|
|
||||||
|
```java
|
||||||
|
// Service에서 예외 발생
|
||||||
|
throw new ApiException(ApiResponseCode.USER_ID_DUPLICATE);
|
||||||
|
|
||||||
|
// Controller에서 예외 처리 (자동)
|
||||||
|
// GlobalExceptionHandler가 ApiException을 잡아서 응답 변환
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 핵심 규칙
|
||||||
|
|
||||||
|
- **오류 코드**: `ApiResponseCode` enum에 모든 오류 정의
|
||||||
|
- **예외 클래스**: `ApiException`으로 비즈니스 로직 예외 처리
|
||||||
|
- **자동 처리**: `GlobalExceptionHandler`가 일관된 응답 형태로 변환
|
||||||
|
@@ -61,6 +61,9 @@ dependencies {
|
|||||||
|
|
||||||
// p6spy
|
// p6spy
|
||||||
implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.9.0'
|
implementation 'com.github.gavlyukovskiy:p6spy-spring-boot-starter:1.9.0'
|
||||||
|
|
||||||
|
// SpringDoc OpenAPI (Swagger)
|
||||||
|
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.9'
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('test') {
|
tasks.named('test') {
|
||||||
|
@@ -6,6 +6,8 @@ import com.bio.bio_backend.domain.user.member.enums.MemberRole;
|
|||||||
import com.bio.bio_backend.domain.user.member.mapper.MemberMapper;
|
import com.bio.bio_backend.domain.user.member.mapper.MemberMapper;
|
||||||
import com.bio.bio_backend.domain.user.member.repository.MemberRepository;
|
import com.bio.bio_backend.domain.user.member.repository.MemberRepository;
|
||||||
import com.bio.bio_backend.domain.user.member.exception.UserDuplicateException;
|
import com.bio.bio_backend.domain.user.member.exception.UserDuplicateException;
|
||||||
|
import com.bio.bio_backend.global.exception.ApiException;
|
||||||
|
import com.bio.bio_backend.global.utils.ApiResponseCode;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.security.core.userdetails.UserDetails;
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
@@ -46,7 +48,7 @@ public class MemberServiceImpl implements MemberService {
|
|||||||
public MemberDto createMember(MemberDto memberDTO) {
|
public MemberDto createMember(MemberDto memberDTO) {
|
||||||
// userId 중복 체크
|
// userId 중복 체크
|
||||||
if (memberRepository.existsByUserId(memberDTO.getUserId())) {
|
if (memberRepository.existsByUserId(memberDTO.getUserId())) {
|
||||||
throw new UserDuplicateException("User ID already exists");
|
throw new ApiException(ApiResponseCode.USER_ID_DUPLICATE);
|
||||||
}
|
}
|
||||||
|
|
||||||
Member member = Member.builder()
|
Member member = Member.builder()
|
||||||
|
@@ -0,0 +1,31 @@
|
|||||||
|
package com.bio.bio_backend.global.config;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
|
import io.swagger.v3.oas.models.info.Info;
|
||||||
|
import io.swagger.v3.oas.models.info.Contact;
|
||||||
|
import io.swagger.v3.oas.models.info.License;
|
||||||
|
import io.swagger.v3.oas.models.servers.Server;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class SwaggerConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public OpenAPI openAPI() {
|
||||||
|
return new OpenAPI()
|
||||||
|
.info(new Info()
|
||||||
|
.title("대상 미생물 분석 시스템 Backend API")
|
||||||
|
.description("대상 미생물 분석 시스템 Backend 서비스의 REST API 문서")
|
||||||
|
.version("v1.0.0")
|
||||||
|
.license(new License()
|
||||||
|
.name("STAM License")
|
||||||
|
.url("https://stam.kr/")))
|
||||||
|
.servers(List.of(
|
||||||
|
new Server().url("http://localhost:8080/service").description("Local Development Server"),
|
||||||
|
new Server().url("https://api.bio.com/service").description("Production Server")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
@@ -0,0 +1,24 @@
|
|||||||
|
package com.bio.bio_backend.global.exception;
|
||||||
|
|
||||||
|
import lombok.Getter;
|
||||||
|
import com.bio.bio_backend.global.utils.ApiResponseCode;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
public class ApiException extends RuntimeException {
|
||||||
|
private final ApiResponseCode responseCode;
|
||||||
|
|
||||||
|
public ApiException(ApiResponseCode responseCode) {
|
||||||
|
super(responseCode.getDescription());
|
||||||
|
this.responseCode = responseCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiException(ApiResponseCode responseCode, String message) {
|
||||||
|
super(message);
|
||||||
|
this.responseCode = responseCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiException(ApiResponseCode responseCode, Throwable cause) {
|
||||||
|
super(responseCode.getDescription(), cause);
|
||||||
|
this.responseCode = responseCode;
|
||||||
|
}
|
||||||
|
}
|
@@ -6,6 +6,7 @@ import org.springframework.http.converter.HttpMessageNotReadableException;
|
|||||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||||
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
import org.springframework.web.servlet.resource.NoResourceFoundException;
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
@@ -73,8 +74,32 @@ public class GlobalExceptionHandler {
|
|||||||
return CustomApiResponse.fail(ApiResponseCode.JSON_PROCESSING_EXCEPTION, null);
|
return CustomApiResponse.fail(ApiResponseCode.JSON_PROCESSING_EXCEPTION, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ExceptionHandler(UserDuplicateException.class)
|
@ExceptionHandler(ApiException.class)
|
||||||
public CustomApiResponse<Void> handleUserDuplicateException(UserDuplicateException e) {
|
public CustomApiResponse<Void> handleApiException(ApiException e) {
|
||||||
return CustomApiResponse.fail(ApiResponseCode.USER_ID_DUPLICATE, null);
|
return CustomApiResponse.fail(e.getResponseCode(), null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||||
|
public CustomApiResponse<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
|
||||||
|
// 검증 실패한 필드들의 상세 오류 정보 추출
|
||||||
|
var errors = e.getBindingResult().getFieldErrors().stream()
|
||||||
|
.map(error -> new ValidationError(error.getField(), error.getDefaultMessage()))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
return CustomApiResponse.fail(ApiResponseCode.ARGUMENT_NOT_VALID, errors);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 검증 오류 상세 정보를 위한 내부 클래스
|
||||||
|
private static class ValidationError {
|
||||||
|
private final String field;
|
||||||
|
private final String message;
|
||||||
|
|
||||||
|
public ValidationError(String field, String message) {
|
||||||
|
this.field = field;
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getField() { return field; }
|
||||||
|
public String getMessage() { return message; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -12,43 +12,29 @@ import org.springframework.http.HttpStatus;
|
|||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
public enum ApiResponseCode {
|
public enum ApiResponseCode {
|
||||||
|
|
||||||
/*login & logout*/
|
|
||||||
|
|
||||||
// 200 OK
|
// 200 OK
|
||||||
LOGIN_SUCCESSFUL(HttpStatus.OK.value(), "Login successful"),
|
LOGIN_SUCCESSFUL(HttpStatus.OK.value(), "Login successful"),
|
||||||
|
|
||||||
LOGOUT_SUCCESSFUL(HttpStatus.OK.value(), "Logout successful"),
|
LOGOUT_SUCCESSFUL(HttpStatus.OK.value(), "Logout successful"),
|
||||||
|
|
||||||
USER_INFO_CHANGE(HttpStatus.OK.value(), "User info update successful"),
|
USER_INFO_CHANGE(HttpStatus.OK.value(), "User info update successful"),
|
||||||
|
|
||||||
USER_DELETE_SUCCESSFUL(HttpStatus.OK.value(), "User delete is successful"),
|
USER_DELETE_SUCCESSFUL(HttpStatus.OK.value(), "User delete is successful"),
|
||||||
|
|
||||||
// 401 Unauthorized
|
|
||||||
USER_NOT_FOUND(HttpStatus.UNAUTHORIZED.value(), "User not found. Authentication failed"),
|
|
||||||
|
|
||||||
AUTHENTICATION_FAILED(HttpStatus.UNAUTHORIZED.value(), "Password is invalid"),
|
|
||||||
|
|
||||||
// 409 Conflict
|
// 409 Conflict
|
||||||
USER_ID_DUPLICATE(HttpStatus.CONFLICT.value(), "User ID already exists"),
|
USER_ID_DUPLICATE(HttpStatus.CONFLICT.value(), "User ID already exists"),
|
||||||
|
|
||||||
/*auth*/
|
|
||||||
// 401 Unauthorized
|
|
||||||
JWT_SIGNATURE_MISMATCH(HttpStatus.UNAUTHORIZED.value(), "JWT signature does not match. Authentication failed"),
|
|
||||||
|
|
||||||
JWT_TOKEN_NULL(HttpStatus.UNAUTHORIZED.value(), "JWT token is null"),
|
|
||||||
|
|
||||||
JWT_TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED.value(), "Token is Expired"),
|
|
||||||
|
|
||||||
All_TOKEN_INVALID(HttpStatus.UNAUTHORIZED.value(), "Access and Refresh tokens are expired or invalid"),
|
|
||||||
|
|
||||||
/*공통 Code*/
|
/*공통 Code*/
|
||||||
// 400 Bad Request
|
// 400 Bad Request
|
||||||
COMMON_BAD_REQUEST(HttpStatus.BAD_REQUEST.value(), "Required request body is missing or Error"),
|
COMMON_BAD_REQUEST(HttpStatus.BAD_REQUEST.value(), "Required request body is missing or Error"),
|
||||||
|
|
||||||
COMMON_FORMAT_WRONG(HttpStatus.BAD_REQUEST.value(), "Request format is incorrect"),
|
COMMON_FORMAT_WRONG(HttpStatus.BAD_REQUEST.value(), "Request format is incorrect"),
|
||||||
|
ARGUMENT_NOT_VALID(HttpStatus.BAD_REQUEST.value(), "Argument is not valid"),
|
||||||
|
|
||||||
// 401 Unauthorized
|
// 401 Unauthorized
|
||||||
COMMON_UNAUTHORIZED(HttpStatus.UNAUTHORIZED.value(), "Unauthorized"),
|
COMMON_UNAUTHORIZED(HttpStatus.UNAUTHORIZED.value(), "Unauthorized"),
|
||||||
|
USER_NOT_FOUND(HttpStatus.UNAUTHORIZED.value(), "User not found. Authentication failed"),
|
||||||
|
AUTHENTICATION_FAILED(HttpStatus.UNAUTHORIZED.value(), "Password is invalid"),
|
||||||
|
JWT_SIGNATURE_MISMATCH(HttpStatus.UNAUTHORIZED.value(), "JWT signature does not match. Authentication failed"),
|
||||||
|
JWT_TOKEN_NULL(HttpStatus.UNAUTHORIZED.value(), "JWT token is null"),
|
||||||
|
JWT_TOKEN_EXPIRED(HttpStatus.UNAUTHORIZED.value(), "Token is Expired"),
|
||||||
|
All_TOKEN_INVALID(HttpStatus.UNAUTHORIZED.value(), "Access and Refresh tokens are expired or invalid"),
|
||||||
|
|
||||||
// 403 Forbidden
|
// 403 Forbidden
|
||||||
COMMON_FORBIDDEN(HttpStatus.FORBIDDEN.value(), "Access is denied"),
|
COMMON_FORBIDDEN(HttpStatus.FORBIDDEN.value(), "Access is denied"),
|
||||||
@@ -61,11 +47,7 @@ public enum ApiResponseCode {
|
|||||||
|
|
||||||
// 500 Internal Server Error
|
// 500 Internal Server Error
|
||||||
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An error occurred on the server"),
|
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An error occurred on the server"),
|
||||||
|
|
||||||
ARGUMENT_NOT_VALID(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Argument is not valid"),
|
|
||||||
|
|
||||||
INDEX_OUT_OF_BOUND(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Index out of bounds for length"),
|
INDEX_OUT_OF_BOUND(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Index out of bounds for length"),
|
||||||
|
|
||||||
JSON_PROCESSING_EXCEPTION(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Check if it is a valid JSON format");
|
JSON_PROCESSING_EXCEPTION(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Check if it is a valid JSON format");
|
||||||
|
|
||||||
private final int statusCode;
|
private final int statusCode;
|
||||||
|
@@ -54,3 +54,11 @@ token.expiration_time_access=180000
|
|||||||
token.expiration_time_refresh=604800000
|
token.expiration_time_refresh=604800000
|
||||||
token.secret_key= c3RhbV9qd3Rfc2VjcmV0X3Rva2Vuc3RhbV9qd3Rfc2VjcmV0X3Rva2Vu
|
token.secret_key= c3RhbV9qd3Rfc2VjcmV0X3Rva2Vuc3RhbV9qd3Rfc2VjcmV0X3Rva2Vu
|
||||||
|
|
||||||
|
# Swagger 설정
|
||||||
|
springdoc.api-docs.path=/api-docs
|
||||||
|
springdoc.swagger-ui.path=/swagger-ui.html
|
||||||
|
springdoc.swagger-ui.operationsSorter=method
|
||||||
|
springdoc.swagger-ui.tagsSorter=alpha
|
||||||
|
springdoc.swagger-ui.doc-expansion=none
|
||||||
|
springdoc.swagger-ui.disable-swagger-default-url=true
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user