From e0e868a2821305ea7200a12cf0dbd9b37ea10396 Mon Sep 17 00:00:00 2001 From: sohot8653 Date: Wed, 13 Aug 2025 13:53:15 +0900 Subject: [PATCH 1/5] =?UTF-8?q?[Swagger=20=EC=B4=88=EA=B8=B0=20=EC=A0=81?= =?UTF-8?q?=EC=9A=A9]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 26 +++++++++++++++- build.gradle | 3 ++ .../global/config/SwaggerConfig.java | 31 +++++++++++++++++++ src/main/resources/application.properties | 8 +++++ 4 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/bio/bio_backend/global/config/SwaggerConfig.java diff --git a/README.md b/README.md index dc03b06..cfbab31 100644 --- a/README.md +++ b/README.md @@ -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. 트랜잭션 관리 #### 기본 설정 diff --git a/build.gradle b/build.gradle index 5753559..ccc0e45 100644 --- a/build.gradle +++ b/build.gradle @@ -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') { diff --git a/src/main/java/com/bio/bio_backend/global/config/SwaggerConfig.java b/src/main/java/com/bio/bio_backend/global/config/SwaggerConfig.java new file mode 100644 index 0000000..1ef3edb --- /dev/null +++ b/src/main/java/com/bio/bio_backend/global/config/SwaggerConfig.java @@ -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") + )); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index cfa157e..09f9612 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -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 + -- 2.28.0.windows.1 From 2ead0f0f12dfe855bbfe28b00957067bf9acb914 Mon Sep 17 00:00:00 2001 From: sohot8653 Date: Wed, 13 Aug 2025 14:39:36 +0900 Subject: [PATCH 2/5] =?UTF-8?q?[=EC=98=A4=EB=A5=98=20=EC=B2=98=EB=A6=AC=20?= =?UTF-8?q?=EA=B0=9C=EC=84=A0]=20-=20ApiException=20=EB=B0=8F=20ApiRespons?= =?UTF-8?q?eCode=20=EC=B6=94=EA=B0=80,=20GlobalExceptionHandler=EC=97=90?= =?UTF-8?q?=EC=84=9C=20ApiException=20=EC=B2=98=EB=A6=AC=20=EB=A1=9C?= =?UTF-8?q?=EC=A7=81=20=EA=B5=AC=ED=98=84,=20README=EC=97=90=20=EC=98=A4?= =?UTF-8?q?=EB=A5=98=20=EB=93=B1=EB=A1=9D=20=EB=B0=8F=20=EC=82=AC=EC=9A=A9?= =?UTF-8?q?=20=EB=B0=A9=EB=B2=95=20=EB=AC=B8=EC=84=9C=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 27 +++++++++++++++ .../member/service/MemberServiceImpl.java | 4 ++- .../global/exception/ApiException.java | 24 +++++++++++++ .../exception/GlobalExceptionHandler.java | 31 +++++++++++++++-- .../global/utils/ApiResponseCode.java | 34 +++++-------------- 5 files changed, 90 insertions(+), 30 deletions(-) create mode 100644 src/main/java/com/bio/bio_backend/global/exception/ApiException.java diff --git a/README.md b/README.md index cfbab31..596ca76 100644 --- a/README.md +++ b/README.md @@ -78,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`가 일관된 응답 형태로 변환 diff --git a/src/main/java/com/bio/bio_backend/domain/user/member/service/MemberServiceImpl.java b/src/main/java/com/bio/bio_backend/domain/user/member/service/MemberServiceImpl.java index 65ed12c..b40f0f4 100644 --- a/src/main/java/com/bio/bio_backend/domain/user/member/service/MemberServiceImpl.java +++ b/src/main/java/com/bio/bio_backend/domain/user/member/service/MemberServiceImpl.java @@ -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() diff --git a/src/main/java/com/bio/bio_backend/global/exception/ApiException.java b/src/main/java/com/bio/bio_backend/global/exception/ApiException.java new file mode 100644 index 0000000..d339468 --- /dev/null +++ b/src/main/java/com/bio/bio_backend/global/exception/ApiException.java @@ -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; + } +} \ No newline at end of file diff --git a/src/main/java/com/bio/bio_backend/global/exception/GlobalExceptionHandler.java b/src/main/java/com/bio/bio_backend/global/exception/GlobalExceptionHandler.java index 558197b..349e4b1 100644 --- a/src/main/java/com/bio/bio_backend/global/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/bio/bio_backend/global/exception/GlobalExceptionHandler.java @@ -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 handleUserDuplicateException(UserDuplicateException e) { - return CustomApiResponse.fail(ApiResponseCode.USER_ID_DUPLICATE, null); + @ExceptionHandler(ApiException.class) + public CustomApiResponse handleApiException(ApiException e) { + return CustomApiResponse.fail(e.getResponseCode(), null); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public CustomApiResponse 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; } } } diff --git a/src/main/java/com/bio/bio_backend/global/utils/ApiResponseCode.java b/src/main/java/com/bio/bio_backend/global/utils/ApiResponseCode.java index e819ef6..0552807 100644 --- a/src/main/java/com/bio/bio_backend/global/utils/ApiResponseCode.java +++ b/src/main/java/com/bio/bio_backend/global/utils/ApiResponseCode.java @@ -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; -- 2.28.0.windows.1 From 6a4388f51397f6c3c2f840f7e1b09537f247e224 Mon Sep 17 00:00:00 2001 From: sohot8653 Date: Wed, 13 Aug 2025 15:23:59 +0900 Subject: [PATCH 3/5] =?UTF-8?q?[Swagger=20=EC=A0=81=EC=9A=A9]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/member/controller/MemberController.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/main/java/com/bio/bio_backend/domain/user/member/controller/MemberController.java b/src/main/java/com/bio/bio_backend/domain/user/member/controller/MemberController.java index 8394e2a..f2efc0b 100644 --- a/src/main/java/com/bio/bio_backend/domain/user/member/controller/MemberController.java +++ b/src/main/java/com/bio/bio_backend/domain/user/member/controller/MemberController.java @@ -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 createMember(@RequestBody @Valid CreateMemberRequestDto requestDto) { MemberDto member = memberMapper.toMemberDto(requestDto); -- 2.28.0.windows.1 From a2c6c83ed750fa5c58bdc12a799d7952db0294d9 Mon Sep 17 00:00:00 2001 From: sohot8653 Date: Wed, 13 Aug 2025 15:38:09 +0900 Subject: [PATCH 4/5] =?UTF-8?q?[Window=20=EB=B2=84=EC=A0=84=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=B3=80=EA=B2=BD]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- nginx-1.28.0/conf/nginx.conf | 46 ++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/nginx-1.28.0/conf/nginx.conf b/nginx-1.28.0/conf/nginx.conf index 571f16a..3fa0ded 100644 --- a/nginx-1.28.0/conf/nginx.conf +++ b/nginx-1.28.0/conf/nginx.conf @@ -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; } } \ No newline at end of file -- 2.28.0.windows.1 From b34636baae364788b081dfb2de567ed629cd4fe6 Mon Sep 17 00:00:00 2001 From: sohot8653 Date: Wed, 13 Aug 2025 15:38:54 +0900 Subject: [PATCH 5/5] =?UTF-8?q?[nginx=20gitignore=20=EC=B6=94=EA=B0=80]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 6d79688..ea16835 100644 --- a/.gitignore +++ b/.gitignore @@ -42,4 +42,5 @@ bin/ # Temporary files created by the OS .DS_Store -Thumbs.db \ No newline at end of file +Thumbs.db +/nginx-1.28.0/logs/nginx.pid -- 2.28.0.windows.1