-
Notifications
You must be signed in to change notification settings - Fork 0
[25.01.11 / TASK-73] Feature - swagger doc #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Walkthrough이 풀 리퀘스트는 프로젝트의 API 문서화를 위해 Swagger를 통합하는 작업을 포함합니다. Changes
Sequence DiagramsequenceDiagram
participant Client
participant Server
participant SwaggerUI
participant APIEndpoints
Client->>Server: Request /api-docs
Server->>SwaggerUI: Serve Swagger Documentation
SwaggerUI-->>Client: Display Interactive API Docs
Client->>APIEndpoints: Make API Requests
APIEndpoints-->>Client: Respond with Data
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 8
🔭 Outside diff range comments (2)
src/types/dto/requests/getPostQuery.type.ts (1)
Line range hint
31-43: 생성자 매개변수가 선택적 속성과 일치하지 않습니다DTO 클래스의 속성은 선택적(
?)으로 정의되어 있지만, 생성자는 필수 매개변수로 정의되어 있습니다.다음과 같이 수정하는 것을 추천드립니다:
- constructor(start: string, end: string) { + constructor(start?: string, end?: string) { this.start = start; this.end = end; }src/routes/post.router.ts (1)
Line range hint
1-2: 사용하지 않는 dotenv 임포트 제거 필요
dotenv패키지를 임포트하고 있지만 실제로는 사용되지 않습니다.다음과 같이 수정하세요:
import express, { Router } from 'express'; -import dotenv from 'dotenv'; import pool from '@/configs/db.config';그리고 아래 라인도 제거하세요:
-dotenv.config();
🧹 Nitpick comments (9)
src/types/dto/requests/loginRequest.type.ts (1)
3-19: Swagger 문서에 예제 값과 상세한 설명이 필요합니다API 문서의 가독성과 이해도를 높이기 위해 예제 값과 더 자세한 설명을 추가하는 것이 좋습니다.
다음과 같이 수정하는 것을 추천드립니다:
/** * @swagger * components: * schemas: * LoginRequestDto: * type: object * required: * - accessToken * - refreshToken * properties: * accessToken: * type: string - * description: accessToken + * description: 사용자 인증을 위한 액세스 토큰 + * example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." * refreshToken: * type: string - * description: refreshToken + * description: 액세스 토큰 갱신을 위한 리프레시 토큰 + * example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." */src/types/dto/responses/baseResponse.type.ts (1)
19-22: 응답 데이터 타입이 구체적이지 않습니다Swagger 문서에서
data속성이 단순히object타입으로 정의되어 있어, 실제 응답 형식을 이해하기 어렵습니다.다음과 같이 수정하는 것을 추천드립니다:
* data: -* type: object +* oneOf: +* - $ref: '#/components/schemas/PostResponseDto' +* - $ref: '#/components/schemas/UserResponseDto' +* - type: 'null' * description: 응답 데이터 (구체적인 타입은 각 엔드포인트에서 정의) * nullable: truesrc/app.ts (1)
30-30: API 라우트 순서 검토 필요Swagger UI 라우트가 API 라우트보다 먼저 정의되어 있습니다. 일반적으로 API 문서화 엔드포인트는 주요 API 라우트 이후에 정의하는 것이 좋습니다.
다음과 같이 라우트 순서를 변경하는 것을 고려해보세요:
-app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec)); app.use('/api', router); +app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));src/types/dto/responses/loginResponse.type.ts (1)
3-51: 스키마 문서에 예시 추가 필요Swagger 문서화가 잘 되어있지만, 각 스키마에 실제 사용 예시를 추가하면 API 사용자의 이해도를 높일 수 있습니다.
각 스키마에 다음과 같이 example을 추가해보세요:
* properties: * thumbnail: * type: string * description: 프로필 이미지 URL +* example: "https://example.com/profile.jpg"* id: * type: integer * description: 사용자 ID +* example: 12345 * username: * type: string * description: 사용자 이름 +* example: "홍길동"src/types/dto/requests/getAllPostsQuery.type.ts (1)
33-36: 커서 파라미터 설명 개선 필요커서 파라미터에 대한 설명이 다소 부족합니다. 페이지네이션을 처음 사용하는 개발자를 위해 더 자세한 설명이 필요합니다.
다음과 같이 설명을 보완해보세요:
* cursor: * type: string -* description: 다음 페이지 조회를 위한 커서값 +* description: | +* 다음 페이지 조회를 위한 커서값 +* * 첫 페이지 조회 시에는 cursor를 전달하지 않음 +* * 응답의 nextCursor 값을 다음 요청의 cursor로 사용 * nullable: true +* example: "2024-01-11T12:00:00.000Z"src/routes/post.router.ts (1)
96-97: 오류 응답에 대한 스키마 참조 누락401 응답에 대한 스키마 정의가 누락되어 있습니다.
다음과 같이 응답 스키마를 추가하세요:
* '401': * description: Post조회 실패 / Unauthorized +* content: +* application/json: +* schema: +* $ref: '#/components/schemas/ErrorResponseDto'src/types/dto/responses/postResponse.type.ts (2)
125-125: 문자열 끝에 불필요한 백틱 문자 제거문서화 중 불필요한 백틱 문자가 발견되었습니다.
다음과 같이 수정하세요:
- description: 게시물 제목` + description: 게시물 제목Also applies to: 16-16
Line range hint
125-144: 응답 예시 추가 권장Swagger 문서에 실제 응답 예시를 추가하면 API 사용자의 이해를 도울 수 있습니다.
다음과 같이 예시를 추가하세요:
* $ref: '#/components/schemas/PostResponseData' +* example: +* success: true +* message: "성공적으로 조회되었습니다" +* data: +* post: +* - date: "2024-01-25" +* dailyViewCount: 100 +* dailyLikeCount: 50package.json (1)
36-37: Swagger 관련 의존성 버전 범위 제한 권장현재 캐럿(^) 범위를 사용하고 있어 예기치 않은 업데이트가 발생할 수 있습니다. 프로덕션 환경의 안정성을 위해 정확한 버전을 지정하는 것이 좋습니다.
다음과 같이 수정하세요:
- "swagger-jsdoc": "^6.2.8", - "swagger-ui-express": "^5.0.1", + "swagger-jsdoc": "6.2.8", + "swagger-ui-express": "5.0.1", - "@types/swagger-jsdoc": "^6.0.4", - "@types/swagger-ui-express": "^4.1.7", + "@types/swagger-jsdoc": "6.0.4", + "@types/swagger-ui-express": "4.1.7",Also applies to: 51-52
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (18)
package.json(2 hunks)src/app.ts(2 hunks)src/configs/swagger.config.ts(1 hunks)src/controllers/tracking.controller.ts(1 hunks)src/repositories/tracking.repository.ts(1 hunks)src/routes/post.router.ts(1 hunks)src/routes/tracking.router.ts(1 hunks)src/routes/user.router.ts(1 hunks)src/services/tracking.service.ts(1 hunks)src/types/dto/requests/eventRequest.type.ts(1 hunks)src/types/dto/requests/getAllPostsQuery.type.ts(2 hunks)src/types/dto/requests/getPostQuery.type.ts(2 hunks)src/types/dto/requests/loginRequest.type.ts(1 hunks)src/types/dto/requests/stayTimeRequest.dto.ts(1 hunks)src/types/dto/responses/baseResponse.type.ts(1 hunks)src/types/dto/responses/emptyReponse.type.ts(1 hunks)src/types/dto/responses/loginResponse.type.ts(1 hunks)src/types/dto/responses/postResponse.type.ts(4 hunks)
✅ Files skipped from review due to trivial changes (6)
- src/services/tracking.service.ts
- src/types/dto/requests/stayTimeRequest.dto.ts
- src/controllers/tracking.controller.ts
- src/repositories/tracking.repository.ts
- src/types/dto/responses/emptyReponse.type.ts
- src/types/dto/requests/eventRequest.type.ts
| /** | ||
| * @swagger | ||
| * components: | ||
| * schemas: | ||
| * GetPostQueryDto: | ||
| * type: object | ||
| * properties: | ||
| * start: | ||
| * type: string | ||
| * format: date | ||
| * description: 조회 시작 날짜 | ||
| * nullable: true | ||
| * end: | ||
| * type: string | ||
| * format: date | ||
| * description: 조회 종료 날짜 | ||
| * nullable: true | ||
| */ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
DTO 속성 타입과 Swagger 문서가 일치하지 않습니다
Swagger 문서에는 nullable: true로 정의되어 있지만, 실제 DTO에서는 string 타입으로 정의되어 있습니다.
다음과 같이 수정하는 것을 추천드립니다:
* start:
* type: string
* format: date
* description: 조회 시작 날짜
-* nullable: true
+* example: "2024-01-01"
* end:
* type: string
* format: date
* description: 조회 종료 날짜
-* nullable: true
+* example: "2024-12-31"📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /** | |
| * @swagger | |
| * components: | |
| * schemas: | |
| * GetPostQueryDto: | |
| * type: object | |
| * properties: | |
| * start: | |
| * type: string | |
| * format: date | |
| * description: 조회 시작 날짜 | |
| * nullable: true | |
| * end: | |
| * type: string | |
| * format: date | |
| * description: 조회 종료 날짜 | |
| * nullable: true | |
| */ | |
| /** | |
| * @swagger | |
| * components: | |
| * schemas: | |
| * GetPostQueryDto: | |
| * type: object | |
| * properties: | |
| * start: | |
| * type: string | |
| * format: date | |
| * description: 조회 시작 날짜 | |
| * example: "2024-01-01" | |
| * end: | |
| * type: string | |
| * format: date | |
| * description: 조회 종료 날짜 | |
| * example: "2024-12-31" | |
| */ |
six-standard
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
전체적으로 문서화가 잘 되서 좋네요~
다만 린팅 규칙이 바뀌신건지 중간 중간 띄어쓰기 제거만 된 파일들이 보이던데, 이 부분들은 왜 이럴련지 궁금합니다!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/configs/swagger.config.ts (1)
1-8: API 문서의 메타데이터를 보강해주세요API 문서의 기본 정보를 더 상세하게 제공하면 좋겠습니다. 다음 항목들의 추가를 고려해주세요:
contact: 개발팀 연락처 정보license: 라이선스 정보termsOfService: 서비스 이용 약관 링크info: { title: 'V.D Project API', version: '1.0.0', description: '모든 API는 로그인 후 진행이 가능합니다.', + contact: { + name: 'V.D Project Team', + email: 'team@example.com' + }, + license: { + name: 'MIT', + url: 'https://opensource.org/licenses/MIT' + } },src/routes/user.router.ts (1)
30-47: 응답 코드 설명 개선 필요현재 응답 코드 설명이 불충분합니다:
- 400: "DTO 검증 실패"는 어떤 검증이 실패했는지 구체적으로 명시해야 합니다.
- 401: 여러 실패 케이스가 한 줄에 나열되어 있어 명확하지 않습니다.
- 500: 구체적인 오류 상황과 해결 방법이 명시되어 있지 않습니다.
각 응답 코드별로 구체적인 설명과 예시를 추가하는 것을 권장합니다. 예시:
* '400': -* description: DTO 검증 실패 +* description: | +* 요청 데이터 검증 실패: +* - 필수 필드 누락 +* - 잘못된 데이터 형식 +* content: +* application/json: +* example: +* success: false +* message: "유효하지 않은 요청 데이터"
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/configs/swagger.config.ts(1 hunks)src/controllers/user.controller.ts(1 hunks)src/routes/tracking.router.ts(1 hunks)src/routes/user.router.ts(1 hunks)src/types/dto/requests/eventRequest.type.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/types/dto/requests/eventRequest.type.ts
- src/routes/tracking.router.ts
🔇 Additional comments (5)
src/configs/swagger.config.ts (3)
9-13: 서버 URL을 환경 변수로 관리해야 합니다현재 서버 URL이 하드코딩되어 있어 개발/스테이징/프로덕션 환경에서 문제가 될 수 있습니다.
14-29:⚠️ Potential issue보안 스키마 구성을 개선해주세요
현재 구현에는 몇 가지 개선이 필요합니다:
- JWT 토큰의 경우 일반적으로
Bearer인증 방식을 사용합니다.- 설명에는 토큰을 헤더, 쿠키, 요청 본문으로 전달할 수 있다고 되어있지만, 설정은 헤더만 지원합니다.
다음과 같이 수정하는 것을 추천드립니다:
components: { securitySchemes: { AccessTokenAuth: { - type: 'apiKey', + type: 'http', + scheme: 'bearer', + bearerFormat: 'JWT', description: 'API 인증을 위한 액세스 토큰입니다. 헤더, 쿠키 또는 요청 본문을 통해 전달할 수 있습니다.', - name: 'access_token', - in: 'header', }, RefreshTokenAuth: { - type: 'apiKey', + type: 'http', + scheme: 'bearer', + bearerFormat: 'JWT', description: '토큰 갱신을 위한 리프레시 토큰입니다. 헤더, 쿠키 또는 요청 본문을 통해 전달할 수 있습니다.', - name: 'refresh_token', - in: 'header', }, }, },Likely invalid or redundant comment.
37-37: API 경로 패턴이 모든 필요한 파일을 포함하는지 확인해주세요현재 설정된 패턴이 모든 API 정의와 타입을 포함하는지 확인이 필요합니다.
다음 스크립트로 Swagger 문서화 관련 파일들을 확인할 수 있습니다:
✅ Verification successful
현재 Swagger 설정의 경로 패턴이 정확합니다
모든 라우트 파일과 타입 정의 파일이 현재 패턴으로 올바르게 포함되어 있습니다:
./src/routes/*.ts: 모든 라우터 파일 포함 (4개 파일)./src/types/**/*.ts: 중첩된 모든 타입 파일 포함 (21개 파일)🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # API 라우트 파일 확인 echo "라우트 파일 목록:" fd -e ts . src/routes echo "\n타입 정의 파일 목록:" fd -e ts . src/types echo "\nSwagger 데코레이터 사용 현황:" rg -l "@swagger|@ApiProperty" src/Length of output: 1592
src/routes/user.router.ts (2)
24-25: 로그인 요청 바디가 필수가 아닌 것으로 명시됨Swagger 문서에서
requestBody가required: false로 설정되어 있습니다. 로그인에는 사용자 정보가 필수적입니다.
66-66: 인증 미들웨어 변경에 대한 검토 필요
authMiddleware.login에서authMiddleware.verify로의 변경이 적절한지 확인이 필요합니다.다음 스크립트를 실행하여 두 미들웨어의 차이점을 확인하세요:
✅ Verification successful
미들웨어 변경이 적절함을 확인했습니다
로그아웃 엔드포인트에서
authMiddleware.verify의 사용이 적절합니다. 이유는 다음과 같습니다:
- 로그아웃은 이미 등록된 사용자를 대상으로 하므로 Velog API 확인이 불필요합니다
verify미들웨어는 토큰 검증과 DB에서의 사용자 존재 여부만 확인하여 더 효율적입니다🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # 미들웨어 구현 비교 ast-grep --pattern 'export const authMiddleware = { $$$ login($$$) { $$$ }, verify($$$) { $$$ } $$$ }'Length of output: 124
Script:
#!/bin/bash # Find potential auth middleware files fd middleware # Search for auth-related files fd auth # Search for login and verify function implementations rg -A 5 "login.*=.*async.*\(|verify.*=.*async.*\(" --type tsLength of output: 842
Script:
#!/bin/bash # View auth middleware implementation cat src/middlewares/auth.middleware.tsLength of output: 3951
| security: [ | ||
| { | ||
| AccessTokenAuth: [], | ||
| RefreshTokenAuth: [], | ||
| }, | ||
| ], |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
보안 요구사항을 엔드포인트 특성에 맞게 조정해주세요
현재 모든 엔드포인트에 AccessTokenAuth와 RefreshTokenAuth가 모두 필요하도록 설정되어 있습니다. 일반적으로:
- 대부분의 엔드포인트는 액세스 토큰만 필요합니다
- 리프레시 토큰은 토큰 갱신 엔드포인트에서만 사용됩니다
다음과 같이 수정하는 것을 추천드립니다:
security: [
{
AccessTokenAuth: [],
- RefreshTokenAuth: [],
},
],그리고 토큰 갱신 엔드포인트에서만 다음과 같이 개별적으로 리프레시 토큰을 요구하도록 설정하세요:
// 토큰 갱신 라우트에서
/**
* @swagger
* /auth/refresh:
* post:
* security:
* - RefreshTokenAuth: []
*/| baseOptions.domain = process.env.ALLOWED_ORIGINS; | ||
| } else { | ||
| baseOptions.domain = 'localhost'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
🛠️ Refactor suggestion
쿠키 도메인 설정이 잘못되었습니다
process.env.ALLOWED_ORIGINS를 쿠키 도메인으로 직접 사용하는 것은 다음과 같은 이유로 작동하지 않습니다:
ALLOWED_ORIGINS는 "http://localhost,http://localhost:3000,https://myapp.com" 형식의 전체 URL 목록을 포함합니다.- 쿠키 도메인은 프로토콜이나 포트 없이 순수한 도메인 이름만 허용합니다.
수정 제안:
if (isProd) {
baseOptions.sameSite = 'lax';
baseOptions.domain = process.env.COOKIE_DOMAIN;
} else {
baseOptions.domain = process.env.COOKIE_DOMAIN || 'localhost';
}🔗 Analysis chain
쿠키 도메인 설정 검토 필요
다음과 같은 잠재적인 문제가 있습니다:
process.env.ALLOWED_ORIGINS는 일반적으로 CORS를 위한 origin 목록을 포함하므로, 쿠키 도메인으로 사용하기에 적절하지 않을 수 있습니다.- 개발 환경에서 'localhost' 하드코딩은 다른 개발 환경(예: Docker, 원격 개발 서버 등)에서 문제를 일으킬 수 있습니다.
다음 스크립트를 실행하여 ALLOWED_ORIGINS 환경 변수의 형식을 확인하세요:
다음과 같이 수정하는 것을 권장합니다:
if (isProd) {
baseOptions.sameSite = 'lax';
- baseOptions.domain = process.env.ALLOWED_ORIGINS;
+ baseOptions.domain = process.env.COOKIE_DOMAIN;
} else {
- baseOptions.domain = 'localhost';
+ baseOptions.domain = process.env.COOKIE_DOMAIN || 'localhost';
}🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# ALLOWED_ORIGINS 환경 변수가 쿠키 도메인으로 적절한지 확인
rg "ALLOWED_ORIGINS.*=.*" .env* || echo "No ALLOWED_ORIGINS found in .env files"
Length of output: 114
Script:
#!/bin/bash
# Check if ALLOWED_ORIGINS is transformed before use
rg -A 3 "ALLOWED_ORIGINS" --type ts
Length of output: 607
변경 사항
Summary by CodeRabbit
새로운 기능
버그 수정
문서화