Skip to content

[25.07.19 / TASK-212] Feature - cache layer, 모듈 추가 #41

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

Open
wants to merge 16 commits into
base: main
Choose a base branch
from

Conversation

Nuung
Copy link
Member

@Nuung Nuung commented Jul 19, 2025

🔥 변경 사항

  • 라이브러리 세팅 & 캐시 활용 모듈 추가
  • 참고로 린팅, 프리티어가 이전에 안먹은 것들이 있어서 이 참에 모두 변경

📸 스크린샷 (UI 변경 시 필수)

image

📌 체크리스트

  • 기능이 정상적으로 동작하는지 테스트 완료
  • 코드 스타일 가이드 준수 여부 확인
  • 관련 문서 업데이트 완료 (필요 시)

Summary by CodeRabbit

  • 신규 기능

    • Redis 기반 캐시 시스템 도입 및 환경변수 추가.
    • /health 엔드포인트 추가로 서버 및 서비스 상태 확인 가능.
    • Redis 캐시 관련 커스텀 에러 클래스와 타입 정의 추가.
    • RedisCache 클래스 구현 및 관련 테스트 추가.
  • 문서

    • .env.sample에 Redis 환경변수 예시 추가.
    • README에 린트 명령어 설명 명확화.
    • package.json에 프로젝트 설명 및 키워드 보완.
  • 버그 수정

    • CORS 및 바디 파서 설정 개선으로 보안 및 안정성 강화.
  • 스타일

    • 코드 전반에 걸친 포맷팅 및 스타일 일관성 향상.
  • 기타

    • 서버 기본 포트 8080으로 변경, graceful shutdown 및 예외 처리 추가.
    • Sentry 초기화 로직 개선 및 상태 확인 기능 추가.

@Nuung Nuung self-assigned this Jul 19, 2025
@Nuung Nuung added documentation Improvements or additions to documentation enhancement New feature or request labels Jul 19, 2025
Copy link

캐싱 도입하기

Copy link
Contributor

coderabbitai bot commented Jul 19, 2025

"""

Walkthrough

Redis 기반 캐시 시스템이 새롭게 도입되어 환경설정, 설정 파일, 캐시 예외, 타입, 구현체 등이 추가되었습니다. Sentry 초기화와 상태 확인, 서버의 그레이스풀 셧다운 및 헬스 체크 엔드포인트가 구현되었습니다. 린트 관련 스크립트와 문서가 개선되었으며, 여러 파일에서 코드 스타일 및 경로가 정리되었습니다.

Changes

파일/그룹 변경 요약
.env.sample Redis 캐시 환경변수 항목 추가
README.md 린트 명령어 설명 및 명칭 정정
package.json 프로젝트 설명, 키워드, 저자, 린트 스크립트, redis 패키지 추가 및 lint-staged 패턴 수정
src/app.ts Redis 캐시 및 Sentry 초기화, trust proxy 조건부 활성화, 바디 파서 제한, CORS 트림, 헬스 체크 엔드포인트, 404 처리 개선, Swagger UI 조건부 제공
src/configs/cache.config.ts Redis 캐시 설정/초기화/종료/상태 확인 모듈 신설
src/configs/db.config.ts logger import 경로 절대경로로 변경
src/configs/sentry.config.ts Sentry 초기화 예외처리 및 상태 반환 함수 추가
src/controllers/user.controller.ts,
src/repositories/user.repository.ts,
src/services/user.service.ts
생성자 및 함수 파라미터 등 코드 스타일 및 포매팅 조정
src/controllers/webhook.controller.ts 상수 키, 문자열, 파라미터, 구조분해 등 코드 스타일 및 포매팅 조정
src/index.ts import 경로 절대화, 포트 8080으로 변경, 서버 인스턴스 변수화, 로깅 강화, 그레이스풀 셧다운 및 예외 처리 추가
src/middlewares/auth.middleware.ts,
src/middlewares/errorHandling.middleware.ts
문자열, 공백 등 코드 스타일 조정
src/modules/cache/cache.exception.ts CacheError, CacheConnectionError, CacheOperationError 예외 클래스 신설
src/modules/cache/cache.type.ts CacheConfig, ICache 인터페이스 신설
src/modules/cache/redis.cache.ts RedisCache 클래스(ICache 구현) 신설, Redis 기반 캐시 기능 제공
src/modules/cache/test/redis.cache.test.ts RedisCache 클래스에 대한 단위 테스트 추가
src/routes/webhook.router.ts 파일 끝 공백 및 개행 정리
src/types/index.ts Sentry 타입 export 구문 통합 및 정리
src/services/post.service.ts 캐시 관련 코드 주석 처리
src/repositories/test/integration/leaderboard.repo.integration.test.ts LeaderboardRepository 통합 테스트 전체 비활성화
eslint.config.mjs ESLint 변수명 규칙에 UPPER_CASE 허용 추가

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ExpressApp
    participant Sentry
    participant RedisCache

    User->>ExpressApp: /health 요청
    ExpressApp->>Sentry: Sentry 상태 확인 (getSentryStatus)
    ExpressApp->>RedisCache: 캐시 상태 확인 (getCacheStatus)
    Sentry-->>ExpressApp: Sentry 상태 반환
    RedisCache-->>ExpressApp: 캐시 상태 반환
    ExpressApp-->>User: 상태/업타임/환경 등 응답
Loading
sequenceDiagram
    participant Process
    participant Server
    participant RedisCache
    participant Sentry

    Process->>Server: SIGTERM/SIGINT 신호 감지
    Server->>RedisCache: disconnect()
    Server->>Sentry: (필요 시) 종료 처리
    Server->>Server: 서버 종료
    Server-->>Process: 정상 종료(exit 0)
    Note over Server: 10초 내 종료 실패 시 강제 종료(exit 1)
Loading

Suggested reviewers

  • six-standard

Poem

🐇
캐시가 생겼어요, Redis와 함께!
헬스 체크도 추가, 서버는 든든해.
Sentry도 꼼꼼히, 상태까지 체크,
린트와 문서도 깔끔하게 정비!
토끼는 깡충, 코드가 반짝—
오늘도 한 걸음, 발전의 도약!
🥕✨
"""

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/cache-layer

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

🧹 Nitpick comments (3)
.env.sample (1)

24-30: 환경변수 키 정렬 권장

순서가 의미에 영향을 주지는 않지만, 일관된 정렬은 PR diff 노이즈를 줄입니다.

-REDIS_HOST=localhost
-REDIS_PORT=6379
-REDIS_PASSWORD=notion-check-plz
-REDIS_DB=0
-REDIS_KEY_PREFIX=vd2:cache:
-CACHE_DEFAULT_TTL=300
+REDIS_HOST=localhost
+REDIS_DB=0
+REDIS_PORT=6379
+REDIS_PASSWORD=notion-check-plz
+REDIS_KEY_PREFIX=vd2:cache:
+CACHE_DEFAULT_TTL=300
package.json (1)

9-9: lint 스크립트 병렬 실행 고려

현재 eslintprettier --check 순차 실행이어서 대규모 코드베이스에서 시간이 오래 걸립니다. npm-run-all -p 등을 이용해 병렬 실행을 검토해 보세요.

src/modules/cache/cache.exception.ts (1)

1-6: 스택 추적 개선을 위한 Error.captureStackTrace 추가 고려

Error 클래스를 상속할 때 스택 추적을 개선하기 위해 Error.captureStackTrace를 사용하는 것이 좋습니다.

 export class CacheError extends Error {
   constructor(message: string, public readonly code?: string) {
     super(message);
     this.name = 'CacheError';
+    Error.captureStackTrace(this, this.constructor);
   }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 42f4be5 and 58ddfa6.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (19)
  • .env.sample (1 hunks)
  • README.md (1 hunks)
  • package.json (4 hunks)
  • src/app.ts (1 hunks)
  • src/configs/cache.config.ts (1 hunks)
  • src/configs/db.config.ts (1 hunks)
  • src/configs/sentry.config.ts (1 hunks)
  • src/controllers/user.controller.ts (1 hunks)
  • src/controllers/webhook.controller.ts (3 hunks)
  • src/index.ts (1 hunks)
  • src/middlewares/auth.middleware.ts (2 hunks)
  • src/middlewares/errorHandling.middleware.ts (1 hunks)
  • src/modules/cache/cache.exception.ts (1 hunks)
  • src/modules/cache/cache.type.ts (1 hunks)
  • src/modules/cache/redis.cache.ts (1 hunks)
  • src/repositories/user.repository.ts (2 hunks)
  • src/routes/webhook.router.ts (1 hunks)
  • src/services/user.service.ts (3 hunks)
  • src/types/index.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (12)
src/controllers/user.controller.ts (2)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/reposities/user.repository.ts:7-15
Timestamp: 2024-12-05T17:21:07.909Z
Learning: Function `findByUserEmail` in `src/reposities/user.repository.ts` is scheduled to be deleted and should be ignored in future code reviews.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/reposities/user.repository.ts:0-0
Timestamp: 2024-12-06T12:07:05.887Z
Learning: `src/services/user.service.ts`에서 `VelogUserLoginDto`를 사용하여 이미 유효성 검증을 진행하므로, `src/repositories/user.repository.ts`의 `createUser` 함수에서는 추가적인 유효성 검증이 필요하지 않다.
src/middlewares/errorHandling.middleware.ts (2)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/error-handling.middleware.ts:1-2
Timestamp: 2024-12-04T14:05:58.537Z
Learning: `src/middlewares/error-handling.middleware.ts` 파일의 에러 핸들링 미들웨어에서 `NextFunction`을 사용하지 않으며, `err`은 커스텀 에러로 사용되므로 `NextFunction`과 `ErrorRequestHandler`를 임포트할 필요가 없습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/error-handling.middleware.ts:4-7
Timestamp: 2024-12-04T13:59:57.198Z
Learning: 프로젝트에서 `Express` 네임스페이스에 `CustomError` 타입이 정의되어 있습니다.
src/services/user.service.ts (9)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/types/dto/user-with-token.dto.ts:3-26
Timestamp: 2024-12-04T13:28:34.692Z
Learning: In `src/types/dto/user-with-token.dto.ts`, since the project is using Express instead of NestJS, `nestjs/swagger` cannot be used. Documentation will be implemented later using an Express-specific Swagger library.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/reposities/user.repository.ts:7-15
Timestamp: 2024-12-05T17:21:07.909Z
Learning: Function `findByUserEmail` in `src/reposities/user.repository.ts` is scheduled to be deleted and should be ignored in future code reviews.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#3
File: src/types/User.type.ts:4-5
Timestamp: 2024-11-28T09:36:44.629Z
Learning: In `src/types/User.type.ts`, the `access_token` and `refresh_token` fields are stored encrypted.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/reposities/user.repository.ts:0-0
Timestamp: 2024-12-06T12:07:05.887Z
Learning: `src/services/user.service.ts`에서 `VelogUserLoginDto`를 사용하여 이미 유효성 검증을 진행하므로, `src/repositories/user.repository.ts`의 `createUser` 함수에서는 추가적인 유효성 검증이 필요하지 않다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/controllers/user.controller.ts:11-12
Timestamp: 2024-12-06T14:29:50.385Z
Learning: TypeScript Express 프로젝트에서, `Express.Request` 인터페이스는 전역으로 확장되어 `user`와 `tokens` 프로퍼티를 포함합니다. `user` 프로퍼티는 `VelogUserLoginResponse | VelogUserVerifyResponse` 타입이고, `tokens`는 `accessToken`과 `refreshToken`을 가진 객체입니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#3
File: src/types/User.type.ts:2-3
Timestamp: 2024-11-28T09:42:54.348Z
Learning: `src/types/User.type.ts` 파일은 `velog_uuid` 컬럼을 응답값에서 그대로 저장하는 용도로 사용되므로, 해당 파일에 대한 코드 리뷰 제안을 하지 않습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/auth.middleware.ts:116-117
Timestamp: 2024-12-04T13:26:58.075Z
Learning: 'velog-dashboard-v2-api' 코드베이스에서는 `src/types/express.d.ts` 파일에서 Express의 `Request` 인터페이스를 확장하여 `user`와 `tokens` 속성을 추가하였습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/repositories/user.repository.ts:9-17
Timestamp: 2024-12-09T05:52:44.165Z
Learning: 이 프로젝트에서는 UUID 검증이 DTO 레이어에서 수행되므로, Repository 클래스(예: `UserRepository`)에서는 추가적인 UUID 검증이 필요하지 않습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/types/dto/velog-user.dto.ts:23-30
Timestamp: 2024-12-09T11:15:44.429Z
Learning: `src/types/dto/velog-user.dto.ts` 파일에서 `ProfileDTO` 클래스는 외부에서 import될 필요가 없으므로 export하지 않아도 된다.
.env.sample (2)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: .env.sample:7-16
Timestamp: 2024-11-29T14:01:55.277Z
Learning: The AES keys provided in the `.env.sample` file are sample values and not actual encryption keys.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: .env.sample:2-6
Timestamp: 2024-11-29T14:01:26.914Z
Learning: `velog-dashboard-v2-api` 프로젝트의 `.env.sample` 파일에서는 데이터베이스 접속 정보를 포함한 환경 변수에 예시 값을 사용하며, 이는 실제 자격 증명이 아니므로 그대로 두어도 됩니다.
src/middlewares/auth.middleware.ts (5)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: src/middlewares/auth.middleware.ts:48-49
Timestamp: 2024-11-29T14:21:32.376Z
Learning: `auth.middleware.ts` 파일에서 `VELOG_API_URL`은 개발 및 배포 환경 모두에서 고정된 값으로, 환경 변수로 이동하지 않고 상수로 설정하여 가독성을 높이는 것이 좋습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/types/dto/user-with-token.dto.ts:3-26
Timestamp: 2024-12-04T13:28:34.692Z
Learning: In `src/types/dto/user-with-token.dto.ts`, since the project is using Express instead of NestJS, `nestjs/swagger` cannot be used. Documentation will be implemented later using an Express-specific Swagger library.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/error-handling.middleware.ts:1-2
Timestamp: 2024-12-04T14:05:58.537Z
Learning: `src/middlewares/error-handling.middleware.ts` 파일의 에러 핸들링 미들웨어에서 `NextFunction`을 사용하지 않으며, `err`은 커스텀 에러로 사용되므로 `NextFunction`과 `ErrorRequestHandler`를 임포트할 필요가 없습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/auth.middleware.ts:116-117
Timestamp: 2024-12-04T13:26:58.075Z
Learning: 'velog-dashboard-v2-api' 코드베이스에서는 `src/types/express.d.ts` 파일에서 Express의 `Request` 인터페이스를 확장하여 `user`와 `tokens` 속성을 추가하였습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/controllers/user.controller.ts:11-12
Timestamp: 2024-12-06T14:29:50.385Z
Learning: TypeScript Express 프로젝트에서, `Express.Request` 인터페이스는 전역으로 확장되어 `user`와 `tokens` 프로퍼티를 포함합니다. `user` 프로퍼티는 `VelogUserLoginResponse | VelogUserVerifyResponse` 타입이고, `tokens`는 `accessToken`과 `refreshToken`을 가진 객체입니다.
src/repositories/user.repository.ts (3)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/reposities/user.repository.ts:7-15
Timestamp: 2024-12-05T17:21:07.909Z
Learning: Function `findByUserEmail` in `src/reposities/user.repository.ts` is scheduled to be deleted and should be ignored in future code reviews.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#3
File: src/types/User.type.ts:4-5
Timestamp: 2024-11-28T09:36:44.629Z
Learning: In `src/types/User.type.ts`, the `access_token` and `refresh_token` fields are stored encrypted.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/types/dto/user-with-token.dto.ts:3-26
Timestamp: 2024-12-04T13:28:34.692Z
Learning: In `src/types/dto/user-with-token.dto.ts`, since the project is using Express instead of NestJS, `nestjs/swagger` cannot be used. Documentation will be implemented later using an Express-specific Swagger library.
package.json (4)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/auth.middleware.ts:116-117
Timestamp: 2024-12-04T13:26:58.075Z
Learning: 'velog-dashboard-v2-api' 코드베이스에서는 `src/types/express.d.ts` 파일에서 Express의 `Request` 인터페이스를 확장하여 `user`와 `tokens` 속성을 추가하였습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: src/middlewares/auth.middleware.ts:48-49
Timestamp: 2024-11-29T14:21:32.376Z
Learning: `auth.middleware.ts` 파일에서 `VELOG_API_URL`은 개발 및 배포 환경 모두에서 고정된 값으로, 환경 변수로 이동하지 않고 상수로 설정하여 가독성을 높이는 것이 좋습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: .env.sample:2-6
Timestamp: 2024-11-29T14:01:26.914Z
Learning: `velog-dashboard-v2-api` 프로젝트의 `.env.sample` 파일에서는 데이터베이스 접속 정보를 포함한 환경 변수에 예시 값을 사용하며, 이는 실제 자격 증명이 아니므로 그대로 두어도 됩니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/types/dto/user-with-token.dto.ts:3-26
Timestamp: 2024-12-04T13:28:34.692Z
Learning: In `src/types/dto/user-with-token.dto.ts`, since the project is using Express instead of NestJS, `nestjs/swagger` cannot be used. Documentation will be implemented later using an Express-specific Swagger library.
src/controllers/webhook.controller.ts (1)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/error-handling.middleware.ts:1-2
Timestamp: 2024-12-04T14:05:58.537Z
Learning: `src/middlewares/error-handling.middleware.ts` 파일의 에러 핸들링 미들웨어에서 `NextFunction`을 사용하지 않으며, `err`은 커스텀 에러로 사용되므로 `NextFunction`과 `ErrorRequestHandler`를 임포트할 필요가 없습니다.
src/app.ts (6)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/types/dto/user-with-token.dto.ts:3-26
Timestamp: 2024-12-04T13:28:34.692Z
Learning: In `src/types/dto/user-with-token.dto.ts`, since the project is using Express instead of NestJS, `nestjs/swagger` cannot be used. Documentation will be implemented later using an Express-specific Swagger library.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/auth.middleware.ts:116-117
Timestamp: 2024-12-04T13:26:58.075Z
Learning: 'velog-dashboard-v2-api' 코드베이스에서는 `src/types/express.d.ts` 파일에서 Express의 `Request` 인터페이스를 확장하여 `user`와 `tokens` 속성을 추가하였습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/error-handling.middleware.ts:1-2
Timestamp: 2024-12-04T14:05:58.537Z
Learning: `src/middlewares/error-handling.middleware.ts` 파일의 에러 핸들링 미들웨어에서 `NextFunction`을 사용하지 않으며, `err`은 커스텀 에러로 사용되므로 `NextFunction`과 `ErrorRequestHandler`를 임포트할 필요가 없습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/controllers/user.controller.ts:11-12
Timestamp: 2024-12-06T14:29:50.385Z
Learning: TypeScript Express 프로젝트에서, `Express.Request` 인터페이스는 전역으로 확장되어 `user`와 `tokens` 프로퍼티를 포함합니다. `user` 프로퍼티는 `VelogUserLoginResponse | VelogUserVerifyResponse` 타입이고, `tokens`는 `accessToken`과 `refreshToken`을 가진 객체입니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: src/middlewares/auth.middleware.ts:48-49
Timestamp: 2024-11-29T14:21:32.376Z
Learning: `auth.middleware.ts` 파일에서 `VELOG_API_URL`은 개발 및 배포 환경 모두에서 고정된 값으로, 환경 변수로 이동하지 않고 상수로 설정하여 가독성을 높이는 것이 좋습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/error-handling.middleware.ts:4-7
Timestamp: 2024-12-04T13:59:57.198Z
Learning: 프로젝트에서 `Express` 네임스페이스에 `CustomError` 타입이 정의되어 있습니다.
src/types/index.ts (5)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/types/dto/velog-user.dto.ts:23-30
Timestamp: 2024-12-09T11:15:44.429Z
Learning: `src/types/dto/velog-user.dto.ts` 파일에서 `ProfileDTO` 클래스는 외부에서 import될 필요가 없으므로 export하지 않아도 된다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/auth.middleware.ts:116-117
Timestamp: 2024-12-04T13:26:58.075Z
Learning: 'velog-dashboard-v2-api' 코드베이스에서는 `src/types/express.d.ts` 파일에서 Express의 `Request` 인터페이스를 확장하여 `user`와 `tokens` 속성을 추가하였습니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/types/dto/user-with-token.dto.ts:3-26
Timestamp: 2024-12-04T13:28:34.692Z
Learning: In `src/types/dto/user-with-token.dto.ts`, since the project is using Express instead of NestJS, `nestjs/swagger` cannot be used. Documentation will be implemented later using an Express-specific Swagger library.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#6
File: src/controllers/user.controller.ts:11-12
Timestamp: 2024-12-06T14:29:50.385Z
Learning: TypeScript Express 프로젝트에서, `Express.Request` 인터페이스는 전역으로 확장되어 `user`와 `tokens` 프로퍼티를 포함합니다. `user` 프로퍼티는 `VelogUserLoginResponse | VelogUserVerifyResponse` 타입이고, `tokens`는 `accessToken`과 `refreshToken`을 가진 객체입니다.
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#3
File: src/types/User.type.ts:2-3
Timestamp: 2024-11-28T09:42:54.348Z
Learning: `src/types/User.type.ts` 파일은 `velog_uuid` 컬럼을 응답값에서 그대로 저장하는 용도로 사용되므로, 해당 파일에 대한 코드 리뷰 제안을 하지 않습니다.
src/index.ts (1)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: src/middlewares/auth.middleware.ts:48-49
Timestamp: 2024-11-29T14:21:32.376Z
Learning: `auth.middleware.ts` 파일에서 `VELOG_API_URL`은 개발 및 배포 환경 모두에서 고정된 값으로, 환경 변수로 이동하지 않고 상수로 설정하여 가독성을 높이는 것이 좋습니다.
src/modules/cache/cache.exception.ts (1)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#5
File: src/middlewares/error-handling.middleware.ts:4-7
Timestamp: 2024-12-04T13:59:57.198Z
Learning: 프로젝트에서 `Express` 네임스페이스에 `CustomError` 타입이 정의되어 있습니다.
🧬 Code Graph Analysis (7)
src/controllers/user.controller.ts (1)
src/services/user.service.ts (1)
  • UserService (12-173)
src/services/user.service.ts (1)
src/repositories/user.repository.ts (1)
  • UserRepository (7-155)
src/middlewares/auth.middleware.ts (1)
src/exception/custom.exception.ts (1)
  • CustomError (1-10)
src/repositories/user.repository.ts (1)
src/types/models/User.type.ts (1)
  • User (1-14)
src/app.ts (5)
src/configs/sentry.config.ts (2)
  • initSentry (9-36)
  • getSentryStatus (39-41)
src/configs/cache.config.ts (2)
  • initCache (23-34)
  • getCacheStatus (48-62)
src/configs/swagger.config.ts (1)
  • options (1-38)
src/exception/notFound.exception.ts (1)
  • NotFoundError (3-7)
src/middlewares/errorHandling.middleware.ts (1)
  • errorHandlingMiddleware (7-32)
src/configs/cache.config.ts (2)
src/modules/cache/cache.type.ts (2)
  • CacheConfig (11-18)
  • ICache (23-80)
src/modules/cache/redis.cache.ts (1)
  • RedisCache (6-190)
src/modules/cache/redis.cache.ts (1)
src/modules/cache/cache.type.ts (2)
  • ICache (23-80)
  • CacheConfig (11-18)
🪛 dotenv-linter (3.3.0)
.env.sample

[warning] 27-27: [UnorderedKey] The REDIS_PASSWORD key should go before the REDIS_PORT key


[warning] 28-28: [UnorderedKey] The REDIS_DB key should go before the REDIS_HOST key


[warning] 29-29: [UnorderedKey] The REDIS_KEY_PREFIX key should go before the REDIS_PASSWORD key


[warning] 30-30: [UnorderedKey] The CACHE_DEFAULT_TTL key should go before the REDIS_DB key

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: build-and-test (23)
  • GitHub Check: build-and-test (21)
  • GitHub Check: build-and-test (20)
  • GitHub Check: build-and-test (22)
🔇 Additional comments (26)
src/routes/webhook.router.ts (1)

53-53: EOL 개행 추가 👍

POSIX 호환성과 Git diff 노이즈 감소에 도움이 됩니다. 기능적인 영향은 없으므로 그대로 두셔도 좋습니다.

src/controllers/user.controller.ts (1)

15-15: 생성자 공백 제거로 코드 스타일 일관성 확보

순수 포맷팅 변경이며 동작에는 영향이 없습니다.

src/services/user.service.ts (3)

13-13: 생성자 포맷팅만 변경

가독성 외에는 영향이 없으므로 문제없습니다.


60-60: undefined 방어 주석 추가

의도를 명확히 해주어 유지보수성을 높입니다.


135-143: 다중 행 인자 정렬로 가독성 개선

인코딩된 토큰 전달 흐름이 더 명확해졌습니다.

src/repositories/user.repository.ts (2)

8-8: 생성자 포맷 변경

사소한 스타일 통일이므로 이상 없습니다.


45-52: 파라미터 목록 개행 → 가독성 향상

SQL placeholder 순서가 명확해져 오류 가능성이 줄어듭니다.

src/configs/db.config.ts (1)

3-4: tsconfig 절대 경로 alias 설정 정상 확인됨 – 런타임 alias도 점검 필요

tsconfig.json에서
compilerOptions.baseUrl: "./src"
compilerOptions.paths["@/*"]: ["*"]
@/configs/logger.configsrc/configs/logger.config로 올바르게 매핑되는 것이 확인되었습니다.

추가로 아래 런타임 환경 설정도 함께 검토해주세요:

  • Webpack 사용 시 webpack.config.jsresolve.alias
  • ts-node 실행 시 tsconfig-paths/register 또는 module-alias 등록 여부

문제 없으면 현 상태 유지하시면 됩니다.

README.md (1)

44-46: lint 명령어 설명 추가 👍

pnpm lintpnpm lint-staged 설명이 실제 스크립트와 일치하도록 갱신된 점 확인했습니다. 문서-스크립트 불일치 이슈를 예방할 수 있어 좋습니다.

src/middlewares/errorHandling.middleware.ts (1)

19-22: 불필요한 공백만 변경 – 별도 조치 불필요

기능적 변화가 없으므로 스킵합니다.

package.json (2)

21-35: 키워드, 설명, author 필드 추가 확인

검색 / npm SEO에 도움이 되므로 긍정적입니다.


47-47: redis 의존성 추가 👍

캐시 레이어 기능 구현을 위한 필수 패키지 추가 확인했습니다. 버전 5.x는 아직 LTS가 아니므로 운영 환경 배포 전 호환성 테스트를 권장합니다.

src/types/index.ts (1)

42-43: 내보내기 구문 통합이 좋습니다.

Sentry 관련 타입들을 그룹화하여 가독성이 향상되었고, 관련 타입들이 함께 관리되어 유지보수에 도움이 됩니다.

src/configs/sentry.config.ts (1)

6-41: Sentry 초기화 및 상태 관리가 잘 구현되었습니다.

다음 개선사항들이 적용되었습니다:

  • 환경변수 검증을 통한 조건부 초기화
  • 적절한 에러 핸들링과 상태 추적
  • 외부에서 상태를 확인할 수 있는 getSentryStatus 함수 제공
  • 초기화 실패 시에도 안전한 처리

헬스체크 엔드포인트와의 연동을 위한 구조가 잘 설계되었습니다.

src/controllers/webhook.controller.ts (1)

9-11: 코드 스타일 정리가 잘 되었습니다.

일관된 형식으로 개선된 부분들:

  • 객체 키의 따옴표 제거로 간결성 향상
  • 문자열 리터럴의 일관된 따옴표 사용
  • 다중 라인 구조분해할당으로 가독성 개선
  • 조건문의 다중 라인 형식으로 명확성 증대

기능적 변경 없이 코드 품질을 향상시킨 좋은 리팩토링입니다.

Also applies to: 14-14, 16-16, 36-41, 56-56

src/app.ts (4)

20-21: 인프라 초기화가 잘 구성되었습니다.

Sentry와 Redis 캐시의 순차적 초기화가 적절하게 구현되었습니다. 각 서비스가 독립적으로 실패해도 애플리케이션이 계속 동작할 수 있도록 설계된 점이 좋습니다.


31-32: 파일 업로드를 위한 제한 설정을 확인해주세요.

10MB 제한이 설정되었는데, 실제 요구사항과 보안 정책에 맞는지 검증이 필요합니다. 대용량 파일 업로드 시 메모리 사용량과 서버 성능에 미치는 영향을 고려해야 합니다.

현재 애플리케이션에서 실제로 파일 업로드 기능이 필요한지, 10MB 제한이 적절한지 검토해주세요.


45-76: 헬스체크 엔드포인트가 잘 구현되었습니다.

다음 장점들이 있습니다:

  • 시스템 상태, 업타임, 환경 정보 제공
  • Sentry와 Redis 캐시 상태 모니터링
  • 적절한 에러 핸들링과 로깅
  • 각 서비스별 독립적인 상태 확인

운영 환경에서 모니터링과 장애 진단에 유용할 것입니다.


86-87: 404 에러 핸들링 개선이 적절합니다.

직접 에러를 던지는 대신 next()를 사용하여 에러 미들웨어로 전달하는 방식으로 변경된 것이 Express의 표준 패턴에 맞습니다. 이를 통해 일관된 에러 처리가 가능합니다.

src/configs/cache.config.ts (2)

23-45: 캐시 생명주기 관리가 잘 구현되었습니다.

다음 장점들이 있습니다:

  • 초기화 실패 시에도 애플리케이션이 계속 실행되는 복원력
  • 적절한 로깅으로 문제 진단 가능
  • 상태 추적을 통한 안전한 종료 처리
  • 에러 상황에서도 안정적인 동작

캐시 연결 실패가 전체 시스템에 영향을 주지 않도록 설계된 점이 우수합니다.


48-62: 헬스체크 구현이 효과적입니다.

실제 Redis 작업(set/get)을 통해 연결 상태를 검증하는 방식이 단순한 ping보다 더 신뢰할 수 있습니다. 1초 TTL을 사용한 임시 키로 테스트하여 캐시에 불필요한 데이터가 남지 않도록 한 점도 좋습니다.

src/index.ts (2)

1-13: 서버 초기화 및 로깅 개선 확인

절대 경로 import 사용과 포트 파싱, 환경별 로깅 분기 처리가 적절하게 구현되었습니다.


15-29: Graceful shutdown 구현 확인

Graceful shutdown이 잘 구현되었습니다. 다만, 10초 타임아웃이 모든 연결을 정리하기에 충분한지 검토가 필요할 수 있습니다.

프로덕션 환경에서 평균적인 연결 종료 시간을 모니터링하여 10초가 적절한지 확인하시기 바랍니다.

src/modules/cache/cache.exception.ts (1)

8-20: 에러 클래스 구조 적절함

캐시 관련 에러를 체계적으로 분류하고 적절한 에러 코드를 부여하는 구조가 잘 설계되었습니다.

src/modules/cache/cache.type.ts (1)

1-80: 캐시 인터페이스 설계 우수

캐시 설정과 서비스 인터페이스가 명확하고 체계적으로 정의되었습니다. 제네릭 타입 사용과 상세한 JSDoc 주석이 특히 좋습니다.

src/modules/cache/redis.cache.ts (1)

12-26: RedisCache 초기화 로직 적절함

설정 기반 초기화와 기본값 처리가 잘 구현되었습니다.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/services/post.service.ts (2)

71-75: 통계 데이터 캐시 조건을 재검토하세요.

totalViews > 0 조건으로 캐시 저장 여부를 결정하는데, 신규 사용자나 조회수가 0인 경우에도 유효한 데이터일 수 있습니다. 조건을 더 포괄적으로 변경하는 것을 고려해보세요.

다음과 같이 수정을 고려해보세요:

-      // if (transformedStatistics.totalViews > 0) {
+      // if (transformedStatistics.lastUpdatedDate) {

42-46: 캐시 TTL 설정 검토: 일간 통계 업데이트 주기에 맞춰 조정하세요.

일별 통계(daily_view_count/daily_like_count)는 posts_postdailystatistics 테이블에서 하루 단위로 갱신되므로, 현재 주석 처리된 5분(300초) TTL은 실제 업데이트 주기와 맞지 않아 캐시 효율이 낮을 수 있습니다. 캐시를 재활성화할 때는 통계 갱신 및 신규 게시물 반영 주기에 맞춰 TTL을 늘려 성능을 개선하는 것을 권장드립니다.

  • 파일: src/services/post.service.ts (42–46행)
  • 캐시 로직 주석 해제 시 TTL 재조정
    • 예: 1시간(3600초) 또는 하루(86400초) 단위로 설정 고려
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 58ddfa6 and e40f352.

📒 Files selected for processing (2)
  • src/modules/cache/__test__/redis.cache.test.ts (1 hunks)
  • src/services/post.service.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/services/post.service.ts (1)
src/repositories/post.repository.ts (1)
  • PostRepository (6-339)
🪛 GitHub Actions: Test CI
src/services/post.service.ts

[error] 1-1: Prettier formatting check failed. Run 'prettier --write' to fix code style issues.

🔇 Additional comments (16)
src/services/post.service.ts (4)

4-4: 캐시 모듈 import가 주석 처리되어 있습니다.

캐시 인프라가 구축되었지만 실제 사용을 위한 import가 비활성화되어 있습니다. 캐시 기능을 활성화할 준비가 되면 주석을 해제해야 합니다.


12-16: 캐시 키 패턴과 로직이 올바르게 구현되어 있습니다.

캐시 키에 사용자 ID, 커서, 정렬 옵션, 정렬 방향, 제한값을 포함하여 캐시 무효화 시나리오를 적절히 고려했습니다. 캐시 히트 시 바로 반환하는 로직도 정확합니다.


37-41: 결과 객체 구조가 일관성 있게 정의되어 있습니다.

캐시된 결과와 새로 조회한 결과의 구조가 동일하여 캐시 활성화 시에도 API 응답 형태가 일관될 것입니다.


55-59: 통계 데이터 캐시 키 패턴이 적절합니다.

사용자별 통계 데이터에 대한 캐시 키가 단순하고 명확하게 정의되어 있습니다.

src/modules/cache/__test__/redis.cache.test.ts (12)

1-29: 모킹 설정과 타입 정의가 잘 구성되어 있습니다.

Redis 클라이언트와 로거에 대한 모킹이 적절히 설정되어 있고, MockRedisClient 인터페이스로 타입 안전성을 보장하고 있습니다.


36-64: 테스트 설정이 포괄적이고 정확합니다.

beforeEach에서 모든 필요한 모킹을 초기화하고, 실제 Redis 설정과 일치하는 테스트 config를 제공하고 있습니다. afterEach에서 모킹을 정리하는 것도 좋은 관행입니다.


70-95: 생성자 테스트가 철저합니다.

Redis 클라이언트 생성 시 전달되는 설정값들과 이벤트 핸들러 등록을 모두 검증하고 있습니다. 기본값 테스트도 포함되어 있어 완성도가 높습니다.


97-125: 연결 관리 테스트가 모든 시나리오를 다룹니다.

정상 연결, 중복 연결 방지, 연결 실패에 대한 테스트가 모두 포함되어 있고, 연결 상태 추적도 올바르게 검증하고 있습니다.


162-212: get 메소드 테스트가 모든 엣지 케이스를 포함합니다.

정상적인 데이터 조회, null 반환, 연결 해제 상태, Redis 오류, JSON 파싱 오류 등 모든 가능한 시나리오를 테스트하고 있습니다. 키 접두사 적용도 올바르게 검증되고 있습니다.


214-274: set 메소드 테스트가 TTL 처리를 포함한 모든 케이스를 다룹니다.

TTL 지정, 기본 TTL 사용, TTL=0인 경우, 연결 해제 상태, 오류 처리 등을 모두 테스트하고 있습니다. setEx와 set 메소드의 구분도 정확히 검증되고 있습니다.


276-317: delete 메소드 테스트가 반환값까지 정확히 검증합니다.

키 존재 여부에 따른 true/false 반환값과 모든 오류 상황에서의 동작을 올바르게 테스트하고 있습니다.


319-360: exists 메소드 테스트가 Redis 반환값을 올바르게 변환합니다.

Redis의 숫자 반환값(1/0)을 boolean으로 정확히 변환하는지 검증하고 있습니다.


362-415: clear 메소드 테스트가 패턴 매칭과 일괄 삭제를 잘 다룹니다.

특정 패턴과 전체 삭제, 빈 결과 처리, 연결 상태 확인 등을 포함한 포괄적인 테스트입니다.


417-459: size 메소드 테스트가 키 개수 계산을 정확히 검증합니다.

모든 오류 상황에서 안전한 기본값(0) 반환을 보장하는 테스트입니다.


461-500: 이벤트 핸들러 테스트가 연결 상태 관리를 철저히 검증합니다.

connect, error, disconnect 이벤트에 대한 핸들러가 올바르게 등록되고 상태를 정확히 업데이트하는지 확인하고 있습니다. 이벤트 핸들러 찾기 로직도 안전하게 구현되어 있습니다.


503-526: private 메소드 테스트로 키 접두사 로직을 확인합니다.

getFullKey 메소드의 동작을 간접적으로 테스트하여 키 접두사가 올바르게 적용되는지 검증하고 있습니다. 빈 키에 대한 처리도 포함되어 있어 완성도가 높습니다.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (3)
src/modules/cache/redis.cache.ts (3)

91-114: JSON 파싱 에러 처리가 잘 구현되었습니다.

이전 리뷰 코멘트에서 제안한 대로 JSON 파싱 에러를 명시적으로 처리하고, 손상된 캐시 데이터를 삭제하는 로직이 적절히 구현되었습니다.


167-204: SCAN을 사용한 안전한 구현입니다.

이전 리뷰 코멘트에서 제안한 대로 KEYS 대신 SCAN을 사용하여 프로덕션 환경에서의 블로킹 문제를 방지했습니다. 배치 처리와 setImmediate를 통한 이벤트 루프 양보도 좋은 접근입니다.


206-235: size 메서드에서도 SCAN을 적절히 사용하고 있습니다.

이전 리뷰 코멘트의 제안대로 KEYS 대신 SCAN을 사용하여 성능 문제를 방지했습니다.

🧹 Nitpick comments (2)
src/modules/cache/redis.cache.ts (2)

167-167: 비동기 처리 최적화 고려사항

setImmediate를 사용한 이벤트 루프 양보는 좋은 접근이지만, Node.js 환경이 아닌 경우를 대비한 폴백 처리를 고려해보세요.

-        await new Promise((resolve) => setImmediate(resolve));
+        await new Promise((resolve) => {
+          if (typeof setImmediate !== 'undefined') {
+            setImmediate(resolve);
+          } else {
+            setTimeout(resolve, 0);
+          }
+        });

Also applies to: 194-195


13-14: 환경 변수 기반 기본값 설정 고려

현재 하드코딩된 기본값 대신 환경 변수에서 읽어오는 것을 고려해보세요. AI 요약에 따르면 .env.sample에 환경 변수가 추가되었다고 합니다.

-    this.keyPrefix = config.keyPrefix || 'vd2:cache:';
-    this.defaultTTL = config.defaultTTL || 300;
+    this.keyPrefix = config.keyPrefix || process.env.REDIS_KEY_PREFIX || 'vd2:cache:';
+    this.defaultTTL = config.defaultTTL || Number(process.env.REDIS_DEFAULT_TTL) || 300;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5c51bdf and 9b1029f.

📒 Files selected for processing (6)
  • eslint.config.mjs (1 hunks)
  • src/configs/db.config.ts (1 hunks)
  • src/index.ts (1 hunks)
  • src/modules/cache/__test__/redis.cache.test.ts (1 hunks)
  • src/modules/cache/redis.cache.ts (1 hunks)
  • src/services/post.service.ts (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/services/post.service.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/configs/db.config.ts
🧰 Additional context used
🧠 Learnings (1)
src/index.ts (1)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: src/middlewares/auth.middleware.ts:48-49
Timestamp: 2024-11-29T14:21:32.376Z
Learning: `auth.middleware.ts` 파일에서 `VELOG_API_URL`은 개발 및 배포 환경 모두에서 고정된 값으로, 환경 변수로 이동하지 않고 상수로 설정하여 가독성을 높이는 것이 좋습니다.
🧬 Code Graph Analysis (1)
src/modules/cache/redis.cache.ts (1)
src/modules/cache/cache.type.ts (2)
  • ICache (23-80)
  • CacheConfig (11-18)
🔇 Additional comments (5)
eslint.config.mjs (1)

51-51: 상수 명명 규칙 지원 추가가 적절합니다.

변수 명명 규칙에 UPPER_CASE 형식을 추가한 것이 좋습니다. 이를 통해 환경 변수나 설정 상수 등을 관례적인 대문자 네이밍으로 사용할 수 있게 되어 코드의 가독성과 일관성이 향상됩니다.

src/index.ts (3)

1-4: Import 경로 개선 및 포트 설정 향상 승인

절대 경로 alias 사용과 parseInt를 통한 명시적 포트 파싱이 코드 가독성과 안정성을 향상시켰습니다.


6-13: 서버 시작 로깅 개선 승인

서버 인스턴스 변수 할당과 환경별 조건부 로깅이 운영 관리와 디버깅에 도움이 됩니다.


15-32: Graceful shutdown 구현 승인

신호 처리, 서버 연결 종료, 강제 종료 타이머를 포함한 graceful shutdown 구현이 운영 환경에서의 안정성을 크게 향상시킵니다.

src/modules/cache/__test__/redis.cache.test.ts (1)

1-547: 테스트 커버리지가 우수합니다!

RedisCache 클래스의 모든 기능을 포괄적으로 테스트하고 있으며, 에러 처리와 엣지 케이스까지 잘 다루고 있습니다. 특히 SCAN을 사용한 페이지네이션 처리와 JSON 파싱 에러 처리 테스트가 포함된 점이 좋습니다.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9b1029f and 905beff.

📒 Files selected for processing (1)
  • src/index.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/index.ts (1)
Learnt from: HA0N1
PR: Check-Data-Out/velog-dashboard-v2-api#4
File: src/middlewares/auth.middleware.ts:48-49
Timestamp: 2024-11-29T14:21:32.376Z
Learning: `auth.middleware.ts` 파일에서 `VELOG_API_URL`은 개발 및 배포 환경 모두에서 고정된 값으로, 환경 변수로 이동하지 않고 상수로 설정하여 가독성을 높이는 것이 좋습니다.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build-and-test (21)
  • GitHub Check: build-and-test (23)
🔇 Additional comments (5)
src/index.ts (5)

1-2: 절대 경로 alias 사용으로 가독성 향상

import 경로를 절대 경로 alias(@/)로 변경하여 코드의 가독성과 유지보수성이 개선되었습니다.


4-4: 포트 설정 개선 확인

기본 포트를 8080으로 변경하고 parseInt를 사용하여 명시적으로 정수 변환하는 것이 좋습니다. 다만 parseInt의 두 번째 인자로 radix 10을 명시한 것도 좋은 개선점입니다.


6-13: 서버 시작 로깅 개선

환경 정보, Swagger 문서 URL (비프로덕션 환경), 헬스체크 엔드포인트 등의 유용한 정보를 포함한 시작 로그가 추가되어 운영 편의성이 향상되었습니다.


15-29: Graceful shutdown 구현 확인

이전 리뷰 피드백에 따라 graceful shutdown이 적절히 구현되었습니다. 10초 타임아웃과 강제 종료 로직도 포함되어 있어 안전한 서버 종료가 가능합니다.


31-32: 시그널 핸들러 구현

SIGTERM과 SIGINT 시그널에 대한 graceful shutdown 핸들러가 적절히 구현되었습니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant