nestjs-clean-typescript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

NestJS Clean TypeScript

NestJS 整洁TypeScript开发规范

Guidelines by Alberto Basalo for developing clean NestJS APIs using TypeScript. These rules emphasize strong typing, clean code principles, and architectural best practices.
由Alberto Basalo制定的,使用TypeScript开发整洁NestJS API的指南。这些规则强调强类型、整洁代码原则和架构最佳实践。

TypeScript General Principles

TypeScript通用原则

  • Always declare the type of each variable and function (parameters and return value)
  • Avoid using any; create necessary types instead
  • Use JSDoc for public classes and methods
  • One export per file
  • 始终声明每个变量和函数(参数及返回值)的类型
  • 避免使用any类型;必要时创建自定义类型
  • 为公共类和方法添加JSDoc注释
  • 每个文件仅导出一个内容

Naming Conventions

命名规范

  • PascalCase for classes
  • camelCase for variables and functions
  • kebab-case for files and directories
  • UPPERCASE for environment variables
  • Boolean variables use prefixes: isX, hasX, canX
  • 类使用PascalCase命名
  • 变量和函数使用camelCase命名
  • 文件和目录使用kebab-case命名
  • 环境变量使用UPPERCASE命名
  • 布尔变量使用前缀:isX、hasX、canX

Function Design

函数设计

  • Write short functions with a single purpose. Less than 20 instructions
  • Use early returns to avoid nesting
  • Apply RO-RO pattern: pass objects for multiple parameters, return objects for results
  • 编写单一职责的短函数,代码行数少于20行
  • 使用提前返回避免嵌套
  • 应用RO-RO模式:多参数时传入对象,返回结果时返回对象

Data and Classes

数据与类

  • Prefer immutability for data with readonly and as const
  • Follow SOLID principles
  • Classes should have:
    • Less than 200 instructions
    • Fewer than 10 public methods
    • Fewer than 10 properties
  • 优先使用readonly和as const实现数据不可变
  • 遵循SOLID原则
  • 类应满足:
    • 代码行数少于200行
    • 公共方法少于10个
    • 属性少于10个

NestJS Specific Guidelines

NestJS特定指南

  • Use modular architecture with one module per domain/route
  • Use MikroORM entities for persistence
  • One service per entity
  • DTOs validated with class-validator
  • Global filters, middlewares, guards, and interceptors in core module
  • 采用模块化架构,每个领域/路由对应一个模块
  • 使用MikroORM实体进行持久化
  • 每个实体对应一个服务
  • 使用class-validator验证DTO
  • 全局过滤器、中间件、守卫和拦截器放在核心模块中

Testing

测试

  • Use Jest framework
  • Follow Arrange-Act-Assert convention
  • Write unit tests for each public function
  • Include end-to-end tests per API module
  • 使用Jest框架
  • 遵循Arrange-Act-Assert约定
  • 为每个公共函数编写单元测试
  • 为每个API模块编写端到端测试