Skip to content

feat(nestjs): add health-check and logger#119

Merged
kagol merged 1 commit intodevfrom
kagol/add-health-check
Oct 10, 2025
Merged

feat(nestjs): add health-check and logger#119
kagol merged 1 commit intodevfrom
kagol/add-health-check

Conversation

@kagol
Copy link
Member

@kagol kagol commented Oct 10, 2025

PR

主要变更:

  • 增加 health-check,用于定期健康检查,在服务挂了时能立马收到通知
  • 增加日志存储,用于现网问题定位
  • 增加环境变量:
    • GLOBAL_PREFIX:用于接口带前缀的场景,用户可以自己修改前缀,默认为:'/',比如可以改成:'/tiny-pro-vue/api'
    • MOCK_REGEX:用户 MOCK 接口 URL 替换,默认为:'/mock',比如可以改成:/\/?tiny-pro-vue\/api\/mock/gim
  • 修复一些拼写错误、ESLint 问题

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Simple health-check endpoint; configurable API global prefix and mock route; structured logging with console + rotating file outputs.
  • Documentation

    • Updated environment example and README with local parallel start instructions.
  • Refactor

    • Replaced loose equality checks with strict comparisons; mock path now driven by env; minor warning text fix.
  • Chores

    • Bumped version to 1.4.0; added dev scripts, new logging dependencies, and ignore rule for logs.

@github-actions github-actions bot added the enhancement New feature or request label Oct 10, 2025
@coderabbitai
Copy link

coderabbitai bot commented Oct 10, 2025

Walkthrough

Bumped top-level package version and added dev scripts; added env entries and .gitignore rule; introduced Winston logging and global prefix in Nest bootstrap; registered a new HealthCheckController; made mock path normalization env-driven; converted several loose == comparisons to strict ===; added logging deps to template package.json.

Changes

Cohort / File(s) Summary
Top-level package
package.json
Version updated 1.3.01.4.0; added scripts: dev, dev:backend.
Template package deps
template/nestJs/package.json
Added dependencies: nest-winston, winston, winston-daily-rotate-file.
Env & gitignore
template/nestJs/.env.example, .gitignore
Added GLOBAL_PREFIX and MOCK_REGEX to env example; PAGINATION_LIMIT line moved (no semantic change); added logs to .gitignore.
Nest bootstrap & logging
template/nestJs/src/main.ts
Integrated winston/nest-winston + DailyRotateFile transports; create app with custom logger; set global prefix from process.env.GLOBAL_PREFIX while excluding healthCheck route.
Health check controller & wiring
template/nestJs/src/health-check.controller.ts, template/nestJs/src/app.module.ts
Added HealthCheckController with GET healthCheck returning "success"; registered controller in AppModule; fixed a warning typo.
Mock controller path normalization
template/nestJs/src/mock/mock.controller.ts
Replaced hard-coded '/mock' with `process.env.MOCK_REGEX
Strict equality fixes
template/nestJs/src/menu/menu.service.ts, template/nestJs/src/permission/permission.service.ts, template/nestJs/src/role/role.service.ts, template/nestJs/src/user/user.service.ts
Replaced loose == comparisons on isInit with strict === checks (true/false cases where applicable).
Docs update
README.md
Added local run instructions for parallel front-end and back-end startup (pnpm commands).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Proc as Process
  participant Nest as NestFactory
  participant Winston as WinstonModule
  participant App as AppModule
  participant Router as Router

  Proc->>Nest: bootstrap()
  Nest->>Winston: createLogger(instance: Console + DailyRotateFile)
  Nest->>App: create(AppModule, { logger })
  App->>Router: setGlobalPrefix(process.env.GLOBAL_PREFIX)
  note over Router: Exclude GET /healthCheck from prefix
  Nest-->>Proc: Application ready
Loading
sequenceDiagram
  autonumber
  participant Client
  participant Router
  participant HC as HealthCheckController

  Client->>Router: GET /healthCheck
  Router->>HC: getEmptyResponse()
  HC-->>Router: "success"
  Router-->>Client: 200 "success"
Loading
sequenceDiagram
  autonumber
  participant Client
  participant Router
  participant Mock as MockController

  Client->>Router: Request /{prefix}/mock/...
  Router->>Mock: getMock/postMock(req)
  Mock->>Mock: path = req.path.replace(process.env.MOCK_REGEX || '/mock', "")
  Mock-->>Router: matched data or 404
  Router-->>Client: response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I hop through logs and rotate the night,
A tiny health check blinks its light.
Env-born paths now twist and bend,
Equals tightened, bugs may end.
A rabbit cheers—deployments bright. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly and accurately summarizes the primary changes—adding a health-check endpoint and logger integration to the NestJS application—which aligns with the main features implemented in this PR.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch kagol/add-health-check

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@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: 4

🧹 Nitpick comments (5)
template/nestJs/.env.example (1)

14-16: LGTM: New environment variables support configurable routing. Add validation for MOCK_REGEX in the mock controller. Align .env.example formatting with project conventions (no spaces around = and no quotes), for example:

PAGINATION_LIMIT=10
GLOBAL_PREFIX=/api
MOCK_REGEX=/mock
template/nestJs/src/main.ts (2)

8-12: Consider using English comments for consistency.

The comment on line 11 is in Chinese (用于存储日志到文件). For international collaboration, consider using English comments throughout the codebase.

Apply this diff:

-import 'winston-daily-rotate-file'; // 用于存储日志到文件
+import 'winston-daily-rotate-file'; // For storing logs to files

17-60: Consider translating Chinese comments to English.

Multiple comments are in Chinese (lines 17, 19, 23, 29, 43, 50, 52). For better international collaboration, consider using English throughout the codebase.

template/nestJs/src/health-check.controller.ts (2)

1-11: Consider using @nestjs/terminus for comprehensive health checks.

The current implementation is a minimal endpoint that always returns success without verifying the actual health of the application (database connectivity, memory usage, disk space, etc.).

Consider using the official @nestjs/terminus package for proper health checks. Based on learnings, NestJS provides robust health check capabilities through this package.

Here's an example implementation:

First, install the package:

npm install --save @nestjs/terminus

Then, update the controller:

-import { Controller, Get } from '@nestjs/common';
+import { Controller, Get } from '@nestjs/common';
+import { HealthCheck, HealthCheckService, TypeOrmHealthIndicator } from '@nestjs/terminus';
 import { Public} from './public/public.decorator';
 
 @Controller('healthCheck')
 export class HealthCheckController {
+  constructor(
+    private health: HealthCheckService,
+    private db: TypeOrmHealthIndicator,
+  ) {}
+
   @Public()
   @Get()
+  @HealthCheck()
-  getEmptyResponse(): string {
-    return 'success'; // 确保健康检查能通过:`curl -k 127.0.0.1:3000/healthCheck` 获取到内容,而不是 404
+  check() {
+    return this.health.check([
+      () => this.db.pingCheck('database'),
+    ]);
   }
 }

You'll also need to import TerminusModule in your AppModule.


9-9: Use English comments for consistency.

The comment is in Chinese. Consider translating to English for better international collaboration:

-    return 'success'; // 确保健康检查能通过:`curl -k 127.0.0.1:3000/healthCheck` 获取到内容,而不是 404
+    return 'success'; // Ensures health check passes: `curl -k 127.0.0.1:3000/healthCheck` returns content instead of 404
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e8940d and 00d905f.

📒 Files selected for processing (10)
  • package.json (1 hunks)
  • template/nestJs/.env.example (1 hunks)
  • template/nestJs/src/app.module.ts (3 hunks)
  • template/nestJs/src/health-check.controller.ts (1 hunks)
  • template/nestJs/src/main.ts (2 hunks)
  • template/nestJs/src/menu/menu.service.ts (1 hunks)
  • template/nestJs/src/mock/mock.controller.ts (2 hunks)
  • template/nestJs/src/permission/permission.service.ts (1 hunks)
  • template/nestJs/src/role/role.service.ts (1 hunks)
  • template/nestJs/src/user/user.service.ts (1 hunks)
🧰 Additional context used
🪛 dotenv-linter (3.3.0)
template/nestJs/.env.example

[warning] 14-14: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 14-14: [UnorderedKey] The PAGINATION_LIMIT key should go before the PAGINATION_PAGE key

(UnorderedKey)


[warning] 15-15: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 15-15: [UnorderedKey] The GLOBAL_PREFIX key should go before the PAGINATION_LIMIT key

(UnorderedKey)


[warning] 16-16: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 16-16: [UnorderedKey] The MOCK_REGEX key should go before the PAGINATION_LIMIT key

(UnorderedKey)

🔇 Additional comments (9)
package.json (1)

3-3: LGTM: Version bump aligns with feature additions.

The patch version increment to 1.3.1 appropriately reflects the addition of health check endpoints, logging enhancements, and code quality improvements across the codebase.

template/nestJs/src/role/role.service.ts (1)

32-32: LGTM: Strict equality improves type safety.

The change from loose (==) to strict (===) equality for the isInit check prevents unexpected type coercion and aligns with JavaScript/TypeScript best practices. This pattern is consistently applied across multiple services in this PR.

template/nestJs/src/menu/menu.service.ts (1)

158-161: LGTM: Consistent strict equality checks.

Both boolean comparisons now use strict equality (===) instead of loose equality (==), preventing unintended type coercion. This change is part of a broader refactoring across the codebase to enforce type-safe comparisons.

template/nestJs/src/permission/permission.service.ts (1)

23-26: LGTM: Type-safe boolean comparisons.

The strict equality operators ensure that isInit is evaluated without type coercion, improving code reliability and consistency with the broader refactoring effort across services.

template/nestJs/src/user/user.service.ts (1)

56-56: LGTM: Strict equality maintains consistency.

This change aligns with the codebase-wide migration to strict equality checks, ensuring type-safe boolean evaluations without coercion.

template/nestJs/src/app.module.ts (3)

62-62: LGTM: Controller registration follows NestJS conventions.

Adding HealthCheckController to the controllers array properly registers it with the NestJS module system, enabling the health check endpoint.


96-96: Good catch: Typo correction.

Fixing the typo from "agin" to "again" improves the clarity of the log message.


37-37: HealthCheckController implementation verified.
template/nestJs/src/health-check.controller.ts exists, exports HealthCheckController, and includes the @Controller('healthCheck') decorator.

template/nestJs/src/main.ts (1)

62-66: LGTM!

The integration of Winston logger with NestJS is correctly implemented using WinstonModule.createLogger.

Comment on lines +17 to +60
// 日志配置
const instance = createLogger({
// 日志选项
transports: [
new winston.transports.Console({
level: 'info',
// 字符串拼接
format: winston.format.combine(
winston.format.timestamp(),
utilities.format.nestLike(),
),
}),
// warn、error日志存储到/logs/application-日期.log文件中
new winston.transports.DailyRotateFile({
level: 'warn',
dirname: 'logs',
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.simple(),
),
}),
// info日志存储到/logs/info-日期.log文件中
new winston.transports.DailyRotateFile({
level: 'info',
dirname: 'logs',
filename: 'info-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
// 文件大小
maxSize: '20m',
// 最多14 天
maxFiles: '14d',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.simple(),
),
}),
],
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Review the hourly log rotation and overlapping log levels.

Several concerns with the logging configuration:

  1. Aggressive rotation: The datePattern: 'YYYY-MM-DD-HH' creates a new log file every hour, which may result in many small files. Consider daily rotation ('YYYY-MM-DD') unless hourly rotation is specifically required.

  2. Overlapping log levels: The 'info' level file transport (lines 44-58) will capture all logs including warnings and errors, duplicating logs already written to the 'warn' file transport (lines 30-42). This means warn/error logs will be written to both files.

  3. Misleading filename: The 'warn' transport (line 33) uses filename: 'application-%DATE%.log' but only captures warn/error levels. Consider a more descriptive name like error-%DATE%.log or adjust the level strategy.

Consider this approach to avoid duplication:

       // warn、error日志存储到/logs/application-日期.log文件中
       new winston.transports.DailyRotateFile({
-        level: 'warn',
+        level: 'error',
         dirname: 'logs',
-        filename: 'application-%DATE%.log',
-        datePattern: 'YYYY-MM-DD-HH',
+        filename: 'error-%DATE%.log',
+        datePattern: 'YYYY-MM-DD',
         zippedArchive: true,
         maxSize: '20m',
         maxFiles: '14d',
         format: winston.format.combine(
           winston.format.timestamp(),
           winston.format.simple(),
         ),
       }),
-      // info日志存储到/logs/info-日期.log文件中
+      // info/warn日志存储到/logs/application-日期.log文件中
       new winston.transports.DailyRotateFile({
         level: 'info',
         dirname: 'logs',
-        filename: 'info-%DATE%.log',
-        datePattern: 'YYYY-MM-DD-HH',
+        filename: 'application-%DATE%.log',
+        datePattern: 'YYYY-MM-DD',
         zippedArchive: true,
         // 文件大小
         maxSize: '20m',

This separates errors into their own file while keeping info/warn logs together, and switches to daily rotation.

📝 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.

Suggested change
// 日志配置
const instance = createLogger({
// 日志选项
transports: [
new winston.transports.Console({
level: 'info',
// 字符串拼接
format: winston.format.combine(
winston.format.timestamp(),
utilities.format.nestLike(),
),
}),
// warn、error日志存储到/logs/application-日期.log文件中
new winston.transports.DailyRotateFile({
level: 'warn',
dirname: 'logs',
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.simple(),
),
}),
// info日志存储到/logs/info-日期.log文件中
new winston.transports.DailyRotateFile({
level: 'info',
dirname: 'logs',
filename: 'info-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
// 文件大小
maxSize: '20m',
// 最多14 天
maxFiles: '14d',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.simple(),
),
}),
],
});
// 日志配置
const instance = createLogger({
// 日志选项
transports: [
new winston.transports.Console({
level: 'info',
// 字符串拼接
format: winston.format.combine(
winston.format.timestamp(),
utilities.format.nestLike(),
),
}),
// warn、error日志存储到/logs/application-日期.log文件中
new winston.transports.DailyRotateFile({
level: 'error',
dirname: 'logs',
- filename: 'application-%DATE%.log',
filename: 'error-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.simple(),
),
}),
// info/warn日志存储到/logs/application-日期.log文件中
new winston.transports.DailyRotateFile({
level: 'info',
dirname: 'logs',
- filename: 'info-%DATE%.log',
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
// 文件大小
maxSize: '20m',
// 最多14 天
maxFiles: '14d',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.simple(),
),
}),
],
});
🤖 Prompt for AI Agents
In template/nestJs/src/main.ts around lines 17 to 60, change the hourly rotation
to daily (datePattern: 'YYYY-MM-DD') and avoid overlapping log writes by
splitting levels: create a DailyRotateFile for errors (filename
'error-%DATE%.log') that only accepts warn/error, and a DailyRotateFile for info
(filename 'info-%DATE%.log') that only accepts info; implement this filtering by
adding a level filter (a small format or custom filter function) on each
transport so warn/error do not also get written to the info file, and update
filenames to be descriptive.

@Get('*')
async getMock(@Req() req: Request) {
const path = req.path.replace('/mock', '');
const path = req.path.replace(process.env.MOCK_REGEX, '');
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Validate and handle missing MOCK_REGEX environment variable.

Using process.env.MOCK_REGEX directly in .replace() has two concerns:

  1. Missing validation: If MOCK_REGEX is undefined, the code will call .replace(undefined, ''), which will fail at runtime.
  2. String vs RegExp: The .env.example defines MOCK_REGEX = '/mock' as a string literal. When passed to .replace(), it performs a simple string replacement (first occurrence only), not a regex match. If regex functionality is intended, convert the string to a RegExp.

Apply this diff to add validation and handle the missing environment variable:

   @Get('*')
   async getMock(@Req() req: Request) {
-    const path = req.path.replace(process.env.MOCK_REGEX, '');
+    const mockRegex = process.env.MOCK_REGEX || '/mock';
+    const path = req.path.replace(mockRegex, '');
     const item = data.filter(

If regex functionality is needed, convert to RegExp:

const mockRegex = new RegExp(process.env.MOCK_REGEX || '/mock', 'g');
const path = req.path.replace(mockRegex, '');
🤖 Prompt for AI Agents
In template/nestJs/src/mock/mock.controller.ts around line 22, the code uses
process.env.MOCK_REGEX directly in req.path.replace which can be undefined and
is treated as a string literal; validate that MOCK_REGEX exists (fall back to a
safe default) and convert it to a RegExp before calling replace. Update the code
to read the env var into a variable with a default (e.g. '/mock'), attempt to
construct a RegExp with appropriate flags (e.g. 'g') catching any construction
errors, and then call req.path.replace using that RegExp so missing or invalid
env values are handled safely.

@Post('*')
async postMock(@Req() req: Request) {
const path = req.path.replace('/mock', '');
const path = req.path.replace(process.env.MOCK_REGEX, '');
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Apply the same validation as in the GET handler.

This POST handler has the same issue with missing validation for process.env.MOCK_REGEX. Apply consistent error handling here as well.

Apply this diff:

   @Post('*')
   async postMock(@Req() req: Request) {
-    const path = req.path.replace(process.env.MOCK_REGEX, '');
+    const mockRegex = process.env.MOCK_REGEX || '/mock';
+    const path = req.path.replace(mockRegex, '');
     const item = data.filter(
🤖 Prompt for AI Agents
In template/nestJs/src/mock/mock.controller.ts around line 34, the POST handler
uses process.env.MOCK_REGEX without the validation present in the GET handler;
add the same checks: verify process.env.MOCK_REGEX is defined, try to construct
a RegExp from it inside a try/catch, and if missing or invalid return or throw a
400/BadRequest with a clear message; then use the validated RegExp to create the
path (e.g., req.path.replace(validatedRegex, '')). Ensure error handling mirrors
the GET handler so both routes behave consistently.

@kagol kagol added the nestjs label Oct 10, 2025
@kagol kagol force-pushed the kagol/add-health-check branch from 00d905f to ddf44a4 Compare October 10, 2025 07:35
@kagol kagol changed the title feat: add health-check and logger feat(nestjs): add health-check and logger Oct 10, 2025
@kagol kagol force-pushed the kagol/add-health-check branch from ddf44a4 to 61f41b3 Compare October 10, 2025 07:36
Copy link

@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: 0

♻️ Duplicate comments (3)
template/nestJs/src/main.ts (1)

17-60: Consider daily rotation and separate error logs to avoid duplication.

The hourly datePattern: 'YYYY-MM-DD-HH' may create many small files. More importantly, the 'info' transport (lines 44-58) captures all logs including warn/error, duplicating entries already written to the 'warn' transport (lines 30-42). This means warn/error logs appear in both application-%DATE%.log and info-%DATE%.log.

Consider switching to daily rotation and splitting transports by level to eliminate duplication:

       new winston.transports.DailyRotateFile({
-        level: 'warn',
+        level: 'error',
         dirname: 'logs',
-        filename: 'application-%DATE%.log',
-        datePattern: 'YYYY-MM-DD-HH',
+        filename: 'error-%DATE%.log',
+        datePattern: 'YYYY-MM-DD',
         zippedArchive: true,
         maxSize: '20m',
         maxFiles: '14d',
         format: winston.format.combine(
           winston.format.timestamp(),
           winston.format.simple(),
         ),
       }),
-      // info日志存储到/logs/info-日期.log文件中
+      // info/warn日志存储到/logs/application-日期.log文件中
       new winston.transports.DailyRotateFile({
         level: 'info',
         dirname: 'logs',
-        filename: 'info-%DATE%.log',
-        datePattern: 'YYYY-MM-DD-HH',
+        filename: 'application-%DATE%.log',
+        datePattern: 'YYYY-MM-DD',
         zippedArchive: true,
         maxSize: '20m',
template/nestJs/src/mock/mock.controller.ts (2)

22-22: Verify string replacement behavior meets requirements.

The code now includes a fallback || '/mock' which addresses the undefined environment variable concern from the past review. However, using .replace() with a string performs only a simple first-occurrence replacement, not a global regex match.

If multiple occurrences of the pattern in the path need to be replaced, convert to a RegExp:

const mockRegexStr = process.env.MOCK_REGEX || '/mock';
const mockRegex = new RegExp(mockRegexStr.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
const path = req.path.replace(mockRegex, '');

Or clarify in documentation that MOCK_REGEX should be a simple prefix string, not a regex pattern. The current .env.example value '/mock' suggests the latter.


34-34: Apply consistent validation in POST handler.

The same string replacement approach is used here. Ensure the behavior is consistent with the GET handler reviewed above.

If you consolidate the path normalization logic, consider extracting it into a helper method:

private normalizePath(path: string): string {
  const mockPrefix = process.env.MOCK_REGEX || '/mock';
  return path.replace(mockPrefix, '');
}

Then use this.normalizePath(req.path) in both handlers.

🧹 Nitpick comments (1)
template/nestJs/.env.example (1)

15-16: Consider documenting the expected format for these variables.

The new environment variables are correctly integrated with the codebase. However, MOCK_REGEX is defined as a simple string literal '/mock' rather than a regex pattern (e.g., '^/mock' or /mock/). The current implementation in mock.controller.ts treats it as a string for simple replacement, not as a regex.

Consider adding inline comments to clarify usage:

 PAGINATION_LIMIT = 10
-GLOBAL_PREFIX = '/api'
-MOCK_REGEX = '/mock'
+# API prefix for all routes except healthCheck
+GLOBAL_PREFIX = '/api'
+# String to strip from mock request paths (not a regex pattern)
+MOCK_REGEX = '/mock'
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 00d905f and 61f41b3.

📒 Files selected for processing (10)
  • package.json (1 hunks)
  • template/nestJs/.env.example (1 hunks)
  • template/nestJs/src/app.module.ts (3 hunks)
  • template/nestJs/src/health-check.controller.ts (1 hunks)
  • template/nestJs/src/main.ts (2 hunks)
  • template/nestJs/src/menu/menu.service.ts (1 hunks)
  • template/nestJs/src/mock/mock.controller.ts (2 hunks)
  • template/nestJs/src/permission/permission.service.ts (1 hunks)
  • template/nestJs/src/role/role.service.ts (1 hunks)
  • template/nestJs/src/user/user.service.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • template/nestJs/src/menu/menu.service.ts
  • package.json
  • template/nestJs/src/role/role.service.ts
  • template/nestJs/src/app.module.ts
  • template/nestJs/src/health-check.controller.ts
🧰 Additional context used
🪛 dotenv-linter (3.3.0)
template/nestJs/.env.example

[warning] 14-14: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 14-14: [UnorderedKey] The PAGINATION_LIMIT key should go before the PAGINATION_PAGE key

(UnorderedKey)


[warning] 15-15: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 15-15: [UnorderedKey] The GLOBAL_PREFIX key should go before the PAGINATION_LIMIT key

(UnorderedKey)


[warning] 16-16: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 16-16: [UnorderedKey] The MOCK_REGEX key should go before the PAGINATION_LIMIT key

(UnorderedKey)

🔇 Additional comments (3)
template/nestJs/src/user/user.service.ts (1)

56-56: LGTM! Strict equality improves type safety.

The change from == to === correctly enforces type-safe comparison and aligns with JavaScript/TypeScript best practices.

template/nestJs/src/permission/permission.service.ts (1)

23-23: LGTM! Strict equality checks are appropriate.

Both changes correctly replace loose equality with strict equality, ensuring type-safe comparisons consistent with the broader codebase cleanup in this PR.

Also applies to: 26-26

template/nestJs/src/main.ts (1)

68-70: LGTM! Default fallback for GLOBAL_PREFIX is present.

The code correctly provides a fallback value '/api' when process.env.GLOBAL_PREFIX is undefined, and appropriately excludes the healthCheck route from the global prefix.

@kagol kagol force-pushed the kagol/add-health-check branch from 61f41b3 to 6d92b86 Compare October 10, 2025 08:00
Copy link

@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: 0

♻️ Duplicate comments (1)
template/nestJs/src/main.ts (1)

30-58: Resolve log duplication and aggressive rotation before shipping.

With Winston’s level hierarchy, the info transport (Line 45) still receives warn/error entries, so every warn/error is written to both files. Coupled with the hourly rotation ('YYYY-MM-DD-HH'), this quickly explodes file counts and storage. Please split the transports by filtering or using levels: ['info']/levels: ['warn','error'] (via custom format), and relax rotation to daily unless you truly need hourly files. The earlier review already called this out, so we should address it now. Based on learnings.

🧹 Nitpick comments (1)
template/nestJs/package.json (1)

39-51: Consider bumping nest‑winston alongside winston v3.

We’re bringing in winston@^3.17.0, but nest-winston@^1.9.7 predates the latest 1.10.x line, which includes type and formatter fixes for v3 flows. Upgrading keeps us on the maintained path and avoids subtle DI/format issues that were resolved after 1.9.x. Based on learnings.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 61f41b3 and 6d92b86.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (13)
  • .gitignore (1 hunks)
  • README.md (1 hunks)
  • package.json (2 hunks)
  • template/nestJs/.env.example (1 hunks)
  • template/nestJs/package.json (2 hunks)
  • template/nestJs/src/app.module.ts (3 hunks)
  • template/nestJs/src/health-check.controller.ts (1 hunks)
  • template/nestJs/src/main.ts (2 hunks)
  • template/nestJs/src/menu/menu.service.ts (1 hunks)
  • template/nestJs/src/mock/mock.controller.ts (2 hunks)
  • template/nestJs/src/permission/permission.service.ts (1 hunks)
  • template/nestJs/src/role/role.service.ts (1 hunks)
  • template/nestJs/src/user/user.service.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🚧 Files skipped from review as they are similar to previous changes (5)
  • template/nestJs/src/health-check.controller.ts
  • package.json
  • template/nestJs/src/menu/menu.service.ts
  • template/nestJs/src/app.module.ts
  • template/nestJs/src/mock/mock.controller.ts
🧰 Additional context used
🪛 dotenv-linter (3.3.0)
template/nestJs/.env.example

[warning] 14-14: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 14-14: [UnorderedKey] The PAGINATION_LIMIT key should go before the PAGINATION_PAGE key

(UnorderedKey)


[warning] 15-15: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 15-15: [UnorderedKey] The GLOBAL_PREFIX key should go before the PAGINATION_LIMIT key

(UnorderedKey)


[warning] 16-16: [SpaceCharacter] The line has spaces around equal sign

(SpaceCharacter)


[warning] 16-16: [UnorderedKey] The MOCK_REGEX key should go before the PAGINATION_LIMIT key

(UnorderedKey)

🔇 Additional comments (4)
template/nestJs/src/permission/permission.service.ts (1)

23-27: Strict equality keeps the init guard precise.

Switching to === prevents unexpected truthy matches if isInit ever arrives as a non-boolean. Looks solid.

README.md (1)

81-92: Local dev steps are clear.

Thanks for documenting the pnpm-based workflow—matches the new scripts nicely.

template/nestJs/src/role/role.service.ts (1)

32-34: Strict comparison matches intent.

isInit now behaves predictably even if callers pass truthy values—looks good.

template/nestJs/src/user/user.service.ts (1)

55-58: Init guard no longer accepts loose truthy values.

Using === keeps the bootstrap import path from triggering on non-boolean inputs. Nice tighten-up.

@kagol kagol merged commit 1fe7a93 into dev Oct 10, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request nestjs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

Comments