code-quality
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode 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:
- passes (no ESLint rule disables).
pnpm --filter <app> lint - passes.
pnpm --filter <app> typecheck - succeeds — mandatory, stricter than typecheck alone.
pnpm --filter <app> build - passes (new features have tests).
pnpm --filter <app> test - Avoid /
anytypes (maintain strict type safety).unknown - Remove statements (use a dedicated logger).
console.log - Ensure error messages are clear and actionable.
在标记任务完成前,请确认:
- 执行通过(不得禁用ESLint规则)。
pnpm --filter <app> lint - 执行通过。
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: (or
pnpm lint)pnpm lint -- --fix - Rule: NEVER disable rules with . Fix the underlying issue.
eslint-disable
Common Fixes:
- : Define a proper interface/DTO.
@typescript-eslint/no-explicit-any - : Remove the variable or prefix with
no-unused-vars._ - : Inject a
no-consoleservice.Logger
我们使用带有严格规则的ESLint。
- 命令:(或
pnpm lint)pnpm lint -- --fix - 规则:绝不能使用禁用规则,应修复根本问题。
eslint-disable
常见修复方案:
- :定义合适的接口/DTO。
@typescript-eslint/no-explicit-any - :移除未使用的变量,或在变量前添加
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:unknowntypescript// 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类型:unknowntypescript// 不良示例 const data: any = req.body; // 良好示例 const data: CreateUserDto = req.body; -
✅ 使用DTO与接口:始终为输入和输出定义数据结构。
-
✅ 信任编译器:如果代码能编译通过,在类型准确的前提下,它大概率能正常运行。
Common Anti-Patterns (General)
常见反模式(通用)
- Ignoring Lint Errors: Address them immediately.
- Logic in Controllers: Controllers should only handle HTTP req/res. Move logic to Services.
- Hardcoded Strings/Magic Numbers: Use constants or enums.
- Complex Conditionals: Break down complex blocks into helper methods.
if/else - Catch-All Error Handling: Avoid just using . Handle specific errors or let global filters handle them.
console.error
- 忽略代码检查错误:应立即解决这些错误。
- 控制器中包含业务逻辑:控制器应仅处理HTTP请求/响应,业务逻辑需移至Services中。
- 硬编码字符串/魔术数字:使用常量或枚举替代。
- 复杂条件判断:将复杂的块拆分为辅助方法。
if/else - 全局捕获错误:避免仅使用,应处理特定错误或交由全局过滤器处理。
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/前端专属模式。