nestjs-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

NestJS Best Practices

NestJS 最佳实践

Comprehensive best practices guide for NestJS applications. Contains 40 rules across 10 categories, prioritized by impact to guide automated refactoring and code generation.
面向NestJS应用的全面最佳实践指南。包含10个类别下的40条规则,按影响程度排序,可指导自动化重构与代码生成。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new NestJS modules, controllers, or services
  • Implementing authentication and authorization
  • Reviewing code for architecture and security issues
  • Refactoring existing NestJS codebases
  • Optimizing performance or database queries
  • Building microservices architectures
在以下场景中参考本指南:
  • 编写新的NestJS模块、控制器或服务
  • 实现身份验证与授权功能
  • 评审代码的架构与安全问题
  • 重构现有NestJS代码库
  • 优化性能或数据库查询
  • 构建微服务架构

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1ArchitectureCRITICAL
arch-
2Dependency InjectionCRITICAL
di-
3Error HandlingHIGH
error-
4SecurityHIGH
security-
5PerformanceHIGH
perf-
6TestingMEDIUM-HIGH
test-
7Database & ORMMEDIUM-HIGH
db-
8API DesignMEDIUM
api-
9MicroservicesMEDIUM
micro-
10DevOps & DeploymentLOW-MEDIUM
devops-
优先级类别影响程度前缀
1架构关键
arch-
2依赖注入关键
di-
3错误处理
error-
4安全
security-
5性能
perf-
6测试中高
test-
7数据库与ORM中高
db-
8API设计
api-
9微服务
micro-
10DevOps与部署低中
devops-

Quick Reference

快速参考

1. Architecture (CRITICAL)

1. 架构(关键)

  • arch-avoid-circular-deps
    - Avoid circular module dependencies
  • arch-feature-modules
    - Organize by feature, not technical layer
  • arch-module-sharing
    - Proper module exports/imports, avoid duplicate providers
  • arch-single-responsibility
    - Focused services over "god services"
  • arch-use-repository-pattern
    - Abstract database logic for testability
  • arch-use-events
    - Event-driven architecture for decoupling
  • arch-avoid-circular-deps
    - 避免模块循环依赖
  • arch-feature-modules
    - 按功能而非技术层组织代码
  • arch-module-sharing
    - 正确进行模块导出/导入,避免重复提供者
  • arch-single-responsibility
    - 专注于单一职责的服务,避免“上帝服务”
  • arch-use-repository-pattern
    - 抽象数据库逻辑以提升可测试性
  • arch-use-events
    - 使用事件驱动架构实现解耦

2. Dependency Injection (CRITICAL)

2. 依赖注入(关键)

  • di-avoid-service-locator
    - Avoid service locator anti-pattern
  • di-interface-segregation
    - Interface Segregation Principle (ISP)
  • di-liskov-substitution
    - Liskov Substitution Principle (LSP)
  • di-prefer-constructor-injection
    - Constructor over property injection
  • di-scope-awareness
    - Understand singleton/request/transient scopes
  • di-use-interfaces-tokens
    - Use injection tokens for interfaces
  • di-avoid-service-locator
    - 避免服务定位器反模式
  • di-interface-segregation
    - 遵循接口隔离原则(ISP)
  • di-liskov-substitution
    - 遵循里氏替换原则(LSP)
  • di-prefer-constructor-injection
    - 优先使用构造函数注入而非属性注入
  • di-scope-awareness
    - 理解单例/请求/瞬态作用域
  • di-use-interfaces-tokens
    - 为接口使用注入令牌

3. Error Handling (HIGH)

3. 错误处理(高)

  • error-use-exception-filters
    - Centralized exception handling
  • error-throw-http-exceptions
    - Use NestJS HTTP exceptions
  • error-handle-async-errors
    - Handle async errors properly
  • error-use-exception-filters
    - 集中式异常处理
  • error-throw-http-exceptions
    - 使用NestJS HTTP异常
  • error-handle-async-errors
    - 正确处理异步错误

4. Security (HIGH)

4. 安全(高)

  • security-auth-jwt
    - Secure JWT authentication
  • security-validate-all-input
    - Validate with class-validator
  • security-use-guards
    - Authentication and authorization guards
  • security-sanitize-output
    - Prevent XSS attacks
  • security-rate-limiting
    - Implement rate limiting
  • security-auth-jwt
    - 安全的JWT身份验证
  • security-validate-all-input
    - 使用class-validator进行验证
  • security-use-guards
    - 使用身份验证与授权守卫
  • security-sanitize-output
    - 防止XSS攻击
  • security-rate-limiting
    - 实现速率限制

5. Performance (HIGH)

5. 性能(高)

  • perf-async-hooks
    - Proper async lifecycle hooks
  • perf-use-caching
    - Implement caching strategies
  • perf-optimize-database
    - Optimize database queries
  • perf-lazy-loading
    - Lazy load modules for faster startup
  • perf-async-hooks
    - 正确使用异步生命周期钩子
  • perf-use-caching
    - 实现缓存策略
  • perf-optimize-database
    - 优化数据库查询
  • perf-lazy-loading
    - 懒加载模块以加快启动速度

6. Testing (MEDIUM-HIGH)

6. 测试(中高)

  • test-use-testing-module
    - Use NestJS testing utilities
  • test-e2e-supertest
    - E2E testing with Supertest
  • test-mock-external-services
    - Mock external dependencies
  • test-use-testing-module
    - 使用NestJS测试工具
  • test-e2e-supertest
    - 使用Supertest进行端到端测试
  • test-mock-external-services
    - 模拟外部依赖

7. Database & ORM (MEDIUM-HIGH)

7. 数据库与ORM(中高)

  • db-use-transactions
    - Transaction management
  • db-avoid-n-plus-one
    - Avoid N+1 query problems
  • db-use-migrations
    - Use migrations for schema changes
  • db-use-transactions
    - 事务管理
  • db-avoid-n-plus-one
    - 避免N+1查询问题
  • db-use-migrations
    - 使用迁移进行 schema 变更

8. API Design (MEDIUM)

8. API设计(中)

  • api-use-dto-serialization
    - DTO and response serialization
  • api-use-interceptors
    - Cross-cutting concerns
  • api-versioning
    - API versioning strategies
  • api-use-pipes
    - Input transformation with pipes
  • api-use-dto-serialization
    - DTO与响应序列化
  • api-use-interceptors
    - 处理横切关注点
  • api-versioning
    - API版本控制策略
  • api-use-pipes
    - 使用管道进行输入转换

9. Microservices (MEDIUM)

9. 微服务(中)

  • micro-use-patterns
    - Message and event patterns
  • micro-use-health-checks
    - Health checks for orchestration
  • micro-use-queues
    - Background job processing
  • micro-use-patterns
    - 消息与事件模式
  • micro-use-health-checks
    - 用于编排的健康检查
  • micro-use-queues
    - 后台任务处理

10. DevOps & Deployment (LOW-MEDIUM)

10. DevOps与部署(低中)

  • devops-use-config-module
    - Environment configuration
  • devops-use-logging
    - Structured logging
  • devops-graceful-shutdown
    - Zero-downtime deployments
  • devops-use-config-module
    - 环境配置
  • devops-use-logging
    - 结构化日志
  • devops-graceful-shutdown
    - 零停机部署

How to Use

使用方法

Read individual rule files for detailed explanations and code examples:
rules/arch-avoid-circular-deps.md
rules/security-validate-all-input.md
rules/_sections.md
Each rule file contains:
  • Brief explanation of why it matters
  • Incorrect code example with explanation
  • Correct code example with explanation
  • Additional context and references
阅读单个规则文件获取详细说明与代码示例:
rules/arch-avoid-circular-deps.md
rules/security-validate-all-input.md
rules/_sections.md
每个规则文件包含:
  • 简要说明该规则的重要性
  • 错误代码示例及解释
  • 正确代码示例及解释
  • 额外背景信息与参考资料

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
包含所有规则详细内容的完整指南:
AGENTS.md