Merge pull request '2025081301' (#2) from 2025081301 into main

Reviewed-on: #2
This commit is contained in:
2025-08-13 15:41:08 +09:00
11 changed files with 200 additions and 50 deletions

3
.gitignore vendored
View File

@@ -42,4 +42,5 @@ bin/
# Temporary files created by the OS
.DS_Store
Thumbs.db
Thumbs.db
/nginx-1.28.0/logs/nginx.pid

View File

@@ -8,6 +8,7 @@
- **Security**: Spring Security + JWT
- **Build Tool**: Gradle
- **Container**: Docker + Kubernetes
- **API Documentation**: Swagger (SpringDoc OpenAPI)
## 개발 가이드
@@ -31,7 +32,30 @@ src/main/java/com/bio/bio_backend/
└── 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` 개별 적용
- **설정**: `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`가 일관된 응답 형태로 변환

View File

@@ -61,6 +61,9 @@ dependencies {
// p6spy
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') {

View File

@@ -1,38 +1,48 @@
# ./nginx/nginx.conf
# 이벤트 블록은 Nginx가 어떻게 연결을 처리할지 정의합니다.
events {
worker_connections 1024;
}
# HTTP 블록은 웹 서버의 동작을 정의합니다.
http {
# MIME 타입 파일을 포함하여 파일 확장자에 따라 콘텐츠 타입을 결정합니다.
include /etc/nginx/mime.types;
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
# (선택) 로그 위치
access_log logs/access.log;
error_log logs/error.log warn;
# 웹소켓용
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
# 기본 서버 설정을 정의합니다.
server {
# 80번 포트에서 요청을 받습니다.
listen 80;
server_name localhost; # 서버 이름을 localhost로 설정
server_name localhost;
# 루트 경로(/)로 들어오는 모든 요청을 처리합니다.
# Nuxt(개발서버 3000)
location / {
# 요청을 다른 서버(여기서는 Nuxt.js)로 전달합니다.
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
# 프록시 헤더를 설정하여 원본 요청 정보를 유지합니다.
# Spring Boot(8080) — /service 접두어 제거
location /service/ {
proxy_pass http://localhost:8080; # 끝에 슬래시 넣으면 /service가 제거됨
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# /api/ 경로로 들어오는 요청을 처리합니다. (Spring Boot 컨테이너를 가리킨다고 가정)
location /service {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# (선택) 업로드 크게 받을 때
# client_max_body_size 50m;
}
}

View File

@@ -1,5 +1,6 @@
package com.bio.bio_backend.domain.user.member.controller;
import com.bio.bio_backend.global.dto.CustomApiResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@@ -16,6 +17,12 @@ import com.bio.bio_backend.domain.user.member.service.MemberService;
import com.bio.bio_backend.domain.user.member.mapper.MemberMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
@RestController
@RequiredArgsConstructor
@@ -26,6 +33,12 @@ public class MemberController {
private final MemberMapper memberMapper;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
@Operation(summary = "회원 가입", description = "새로운 회원을 등록합니다.", tags = {"Member"})
@ApiResponses({
@ApiResponse(responseCode = "201", description = "회원 가입 성공", content = @Content(schema = @Schema(implementation = CreateMemberResponseDto.class))),
@ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content(schema = @Schema(implementation = CustomApiResponse.class))),
@ApiResponse(responseCode = "409", description = "중복된 사용자 정보", content = @Content(schema = @Schema(implementation = CustomApiResponse.class)))
})
@PostMapping("/members")
public ResponseEntity<CreateMemberResponseDto> createMember(@RequestBody @Valid CreateMemberRequestDto requestDto) {
MemberDto member = memberMapper.toMemberDto(requestDto);

View File

@@ -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.repository.MemberRepository;
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.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
@@ -46,7 +48,7 @@ public class MemberServiceImpl implements MemberService {
public MemberDto createMember(MemberDto memberDTO) {
// userId 중복 체크
if (memberRepository.existsByUserId(memberDTO.getUserId())) {
throw new UserDuplicateException("User ID already exists");
throw new ApiException(ApiResponseCode.USER_ID_DUPLICATE);
}
Member member = Member.builder()

View File

@@ -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")
));
}
}

View File

@@ -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;
}
}

View File

@@ -6,6 +6,7 @@ import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.servlet.resource.NoResourceFoundException;
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -73,8 +74,32 @@ public class GlobalExceptionHandler {
return CustomApiResponse.fail(ApiResponseCode.JSON_PROCESSING_EXCEPTION, null);
}
@ExceptionHandler(UserDuplicateException.class)
public CustomApiResponse<Void> handleUserDuplicateException(UserDuplicateException e) {
return CustomApiResponse.fail(ApiResponseCode.USER_ID_DUPLICATE, null);
@ExceptionHandler(ApiException.class)
public CustomApiResponse<Void> handleApiException(ApiException e) {
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; }
}
}

View File

@@ -11,44 +11,30 @@ import org.springframework.http.HttpStatus;
@Getter
@AllArgsConstructor
public enum ApiResponseCode {
/*login & logout*/
// 200 OK
LOGIN_SUCCESSFUL(HttpStatus.OK.value(), "Login successful"),
LOGOUT_SUCCESSFUL(HttpStatus.OK.value(), "Logout successful"),
USER_INFO_CHANGE(HttpStatus.OK.value(), "User info update 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
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*/
// 400 Bad Request
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"),
ARGUMENT_NOT_VALID(HttpStatus.BAD_REQUEST.value(), "Argument is not valid"),
// 401 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
COMMON_FORBIDDEN(HttpStatus.FORBIDDEN.value(), "Access is denied"),
@@ -61,11 +47,7 @@ public enum ApiResponseCode {
// 500 Internal Server Error
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"),
JSON_PROCESSING_EXCEPTION(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Check if it is a valid JSON format");
private final int statusCode;

View File

@@ -54,3 +54,11 @@ token.expiration_time_access=180000
token.expiration_time_refresh=604800000
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