code-quality

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Quality Skill

代码质量技能指南

Provides general code quality and best practices guidance applicable across languages and frameworks. Focuses on Linting, Testing, and Type Safety.
For architecture-specific patterns (N+1 queries, Soft Deletes, etc.), refer to:
  • Database Patterns
  • Service Patterns
  • Repository Patterns
提供适用于各类语言与框架的通用代码质量及最佳实践指南,重点关注代码检查(Linting)测试类型安全
针对特定架构模式(如N+1查询、软删除等),请参考:
  • 数据库模式
  • 服务模式
  • 仓储模式

Pre-Submission Checklist

提交前检查清单

Before marking any task as complete:
  • pnpm --filter <app> lint
    passes (no ESLint rule disables).
  • pnpm --filter <app> typecheck
    passes.
  • pnpm --filter <app> build
    succeeds — mandatory, stricter than typecheck alone.
  • pnpm --filter <app> test
    passes (new features have tests).
  • Avoid
    any
    /
    unknown
    types (maintain strict type safety).
  • Remove
    console.log
    statements (use a dedicated logger).
  • Ensure error messages are clear and actionable.
在标记任务完成前,请确认:
  • pnpm --filter <app> lint
    执行通过(不得禁用ESLint规则)。
  • pnpm --filter <app> typecheck
    执行通过。
  • pnpm --filter <app> build
    执行成功——此步骤为必填项,比单独的类型检查更严格。
  • pnpm --filter <app> test
    执行通过(新功能需包含测试用例)。
  • 避免使用
    any
    /
    unknown
    类型(保持严格的类型安全)。
  • 移除
    console.log
    语句(使用专用日志工具)。
  • 确保错误信息清晰且可执行。

Linting

代码检查(Linting)

We use ESLint with strict rules.
  • Command:
    pnpm lint
    (or
    pnpm lint -- --fix
    )
  • Rule: NEVER disable rules with
    eslint-disable
    . Fix the underlying issue.
Common Fixes:
  • @typescript-eslint/no-explicit-any
    : Define a proper interface/DTO.
  • no-unused-vars
    : Remove the variable or prefix with
    _
    .
  • no-console
    : Inject a
    Logger
    service.
我们使用带有严格规则的ESLint。
  • 命令
    pnpm lint
    (或
    pnpm lint -- --fix
  • 规则:绝不能使用
    eslint-disable
    禁用规则,应修复根本问题。
常见修复方案
  • @typescript-eslint/no-explicit-any
    :定义合适的接口/DTO。
  • no-unused-vars
    :移除未使用的变量,或在变量前添加
    _
    前缀。
  • no-console
    :注入
    Logger
    服务。

Testing

测试

All new features require tests.
  • Unit Tests: Test individual classes (Services, Utils) with mocked dependencies.
  • Integration Tests: Test interactions (Repositories) with real database/services.
Example (Unit Test):
typescript
describe('UserService', () => {
  it('should return user when found', async () => {
    // 1. Arrange (Mock dependencies)
    const mockRepo = { findByUid: vi.fn().mockResolvedValue(user) };  // Vitest — not jest.fn()
    const service = new UserService(mockRepo as any);
 
    // 2. Act
    const result = await service.getUser('u_1');
 
    // 3. Assert
    expect(result).toEqual(user);
    expect(mockRepo.findByUid).toHaveBeenCalledWith('u_1');
  });
});
所有新功能都需要编写测试。
  • 单元测试:测试独立类(如Services、Utils)时使用模拟依赖
  • 集成测试:测试交互逻辑(如Repositories)时使用真实数据库/服务
示例(单元测试):
typescript
describe('UserService', () => {
  it('should return user when found', async () => {
    // 1. Arrange (Mock dependencies)
    const mockRepo = { findByUid: vi.fn().mockResolvedValue(user) };  // Vitest — not jest.fn()
    const service = new UserService(mockRepo as any);
 
    // 2. Act
    const result = await service.getUser('u_1');
 
    // 3. Assert
    expect(result).toEqual(user);
    expect(mockRepo.findByUid).toHaveBeenCalledWith('u_1');
  });
});

TypeScript Type Safety

TypeScript类型安全

Strict mode is enforced.
  • Avoid
    any
    /
    unknown
    :
    typescript
    // BAD
    const data: any = req.body;
    
    // GOOD
    const data: CreateUserDto = req.body;
  • Use DTOs and Interfaces: Always define shapes for inputs and outputs.
  • Trust the Compiler: If it compiles, it should likely run (if types are accurate).
强制启用严格模式。
  • 避免使用
    any
    /
    unknown
    类型
    typescript
    // 不良示例
    const data: any = req.body;
    
    // 良好示例
    const data: CreateUserDto = req.body;
  • 使用DTO与接口:始终为输入和输出定义数据结构。
  • 信任编译器:如果代码能编译通过,在类型准确的前提下,它大概率能正常运行。

Common Anti-Patterns (General)

常见反模式(通用)

  1. Ignoring Lint Errors: Address them immediately.
  2. Logic in Controllers: Controllers should only handle HTTP req/res. Move logic to Services.
  3. Hardcoded Strings/Magic Numbers: Use constants or enums.
  4. Complex Conditionals: Break down complex
    if/else
    blocks into helper methods.
  5. Catch-All Error Handling: Avoid just using
    console.error
    . Handle specific errors or let global filters handle them.
  1. 忽略代码检查错误:应立即解决这些错误。
  2. 控制器中包含业务逻辑:控制器应仅处理HTTP请求/响应,业务逻辑需移至Services中。
  3. 硬编码字符串/魔术数字:使用常量或枚举替代。
  4. 复杂条件判断:将复杂的
    if/else
    块拆分为辅助方法。
  5. 全局捕获错误:避免仅使用
    console.error
    ,应处理特定错误或交由全局过滤器处理。

Related Skills

相关技能

  • Database Patterns: N+1 queries, Soft Deletes, Bulk Operations.
  • Service Pattern NestJS: Business logic errors, Transactions.
  • Repository Pattern NestJS: Data access rules.
  • Backend Controller Pattern NestJS: NestJS-specific controller rules.
  • Frontend Code Quality: React/Frontend specific patterns.
  • 数据库模式:N+1查询、软删除、批量操作。
  • NestJS服务模式:业务逻辑错误、事务处理。
  • NestJS仓储模式:数据访问规则。
  • NestJS后端控制器模式:NestJS专属控制器规则。
  • 前端代码质量:React/前端专属模式。