- 统一文件命名为snake_case格式(kebab-case snake_case) - 重构zulip模块为zulip_core,明确Core层职责 - 重构user-mgmt模块为user_mgmt,统一命名规范 - 调整模块依赖关系,优化架构分层 - 删除过时的文件和目录结构 - 更新相关文档和配置文件 本次重构涉及大量文件重命名和模块重组, 旨在建立更清晰的项目架构和统一的命名规范。
959 lines
27 KiB
Markdown
959 lines
27 KiB
Markdown
# 开发者代码检查规范
|
||
|
||
## 📖 概述
|
||
|
||
本文档为开发者提供全面的代码检查规范,确保代码质量、可维护性和团队协作效率。规范涵盖命名、注释、代码质量、架构分层、测试覆盖和文档生成六个核心方面。
|
||
|
||
## 🎯 检查流程
|
||
|
||
代码检查分为6个步骤,建议按顺序执行:
|
||
|
||
1. **命名规范检查** - 文件、变量、函数、类的命名规范
|
||
2. **注释规范检查** - 文件头、类、方法注释的完整性
|
||
3. **代码质量检查** - 代码清洁度、性能优化
|
||
4. **架构分层检查** - 分层架构的合规性
|
||
5. **测试覆盖检查** - 测试文件的完整性和覆盖率
|
||
6. **功能文档生成** - README文档的生成和维护
|
||
|
||
---
|
||
|
||
## 1️⃣ 命名规范检查
|
||
|
||
### 📁 文件和文件夹命名
|
||
|
||
**核心规则:使用下划线分隔(snake_case)**
|
||
|
||
```typescript
|
||
✅ 正确示例:
|
||
- user_controller.ts
|
||
- player_service.ts
|
||
- create_room_dto.ts
|
||
- src/business/auth/
|
||
- src/core/db/users/
|
||
|
||
❌ 错误示例:
|
||
- UserController.ts # 大驼峰命名
|
||
- playerService.ts # 小驼峰命名
|
||
- base-users.service.ts # 短横线分隔(常见错误!)
|
||
- src/Business/Auth/ # 大驼峰命名
|
||
```
|
||
|
||
**⚠️ 特别注意:短横线(kebab-case)是最常见的文件命名错误!**
|
||
|
||
### 🏗️ 文件夹结构优化
|
||
|
||
**避免过度嵌套,减少单文件文件夹**
|
||
|
||
```typescript
|
||
❌ 错误:过度嵌套
|
||
src/
|
||
guards/
|
||
auth.guard.ts # 只有一个文件,不需要单独文件夹
|
||
interceptors/
|
||
logging.interceptor.ts # 只有一个文件,不需要单独文件夹
|
||
|
||
✅ 正确:扁平化结构
|
||
src/
|
||
auth.guard.ts
|
||
logging.interceptor.ts
|
||
```
|
||
|
||
**文件夹创建判断标准:**
|
||
- 不超过3个文件:移到上级目录(扁平化)
|
||
- 4个以上文件:可以保持独立文件夹
|
||
- 完整功能模块:即使文件较少也可以保持独立(需特殊说明)
|
||
|
||
**检查方法(重要):**
|
||
1. **必须使用工具详细检查**:不能凭印象判断文件夹内容
|
||
2. **逐个统计文件数量**:使用`listDirectory(path, depth=2)`获取准确数据
|
||
3. **识别单文件文件夹**:只有1个文件的文件夹必须扁平化
|
||
4. **更新引用路径**:移动文件后必须更新所有import语句
|
||
|
||
**常见检查错误:**
|
||
- ❌ 只看到文件夹存在就认为结构合理
|
||
- ❌ 没有统计每个文件夹的文件数量
|
||
- ❌ 凭印象判断而不使用工具验证
|
||
- ❌ 遗漏单文件文件夹的识别
|
||
|
||
**正确检查流程:**
|
||
1. 使用listDirectory工具查看详细结构
|
||
2. 逐个文件夹统计文件数量
|
||
3. 识别需要扁平化的文件夹(≤3个文件)
|
||
4. 执行文件移动和路径更新操作
|
||
|
||
### 🔤 变量和函数命名
|
||
|
||
**规则:小驼峰命名(camelCase)**
|
||
|
||
```typescript
|
||
✅ 正确示例:
|
||
const userName = 'Alice';
|
||
function getUserInfo() { }
|
||
async function validateUser() { }
|
||
const isGameStarted = false;
|
||
|
||
❌ 错误示例:
|
||
const UserName = 'Alice';
|
||
function GetUserInfo() { }
|
||
const is_game_started = false;
|
||
```
|
||
### 🏷️ 类和接口命名
|
||
|
||
**规则:大驼峰命名(PascalCase)**
|
||
|
||
```typescript
|
||
✅ 正确示例:
|
||
class UserService { }
|
||
interface GameConfig { }
|
||
class CreateUserDto { }
|
||
enum UserStatus { }
|
||
|
||
❌ 错误示例:
|
||
class userService { }
|
||
interface gameConfig { }
|
||
class createUserDto { }
|
||
```
|
||
|
||
### 📊 常量命名
|
||
|
||
**规则:全大写 + 下划线分隔(SCREAMING_SNAKE_CASE)**
|
||
|
||
```typescript
|
||
✅ 正确示例:
|
||
const PORT = 3000;
|
||
const MAX_PLAYERS = 10;
|
||
const SALT_ROUNDS = 10;
|
||
const DEFAULT_TIMEOUT = 5000;
|
||
|
||
❌ 错误示例:
|
||
const port = 3000;
|
||
const maxPlayers = 10;
|
||
const saltRounds = 10;
|
||
```
|
||
|
||
### 🛣️ 路由命名
|
||
|
||
**规则:全小写 + 短横线分隔(kebab-case)**
|
||
|
||
```typescript
|
||
✅ 正确示例:
|
||
@Get('user/get-info')
|
||
@Post('room/join-room')
|
||
@Put('player/update-position')
|
||
|
||
❌ 错误示例:
|
||
@Get('user/getInfo')
|
||
@Post('room/joinRoom')
|
||
@Put('player/update_position')
|
||
```
|
||
|
||
---
|
||
|
||
## 2️⃣ 注释规范检查
|
||
|
||
### 📄 文件头注释
|
||
|
||
**必须包含的信息:**
|
||
|
||
```typescript
|
||
/**
|
||
* 文件功能描述
|
||
*
|
||
* 功能描述:
|
||
* - 主要功能点1
|
||
* - 主要功能点2
|
||
* - 主要功能点3
|
||
*
|
||
* 职责分离:
|
||
* - 职责描述1
|
||
* - 职责描述2
|
||
*
|
||
* 最近修改:
|
||
* - 2024-01-07: 代码规范优化 - 修复命名规范问题 (修改者: 张三)
|
||
* - 2024-01-06: 功能新增 - 添加用户验证功能 (修改者: 李四)
|
||
*
|
||
* @author 原始作者名称
|
||
* @version 1.0.1
|
||
* @since 2024-01-01
|
||
* @lastModified 2024-01-07
|
||
*/
|
||
```
|
||
|
||
### 🏛️ 类注释
|
||
|
||
**必须包含的信息:**
|
||
|
||
```typescript
|
||
/**
|
||
* 类功能描述
|
||
*
|
||
* 职责:
|
||
* - 主要职责1
|
||
* - 主要职责2
|
||
*
|
||
* 主要方法:
|
||
* - method1() - 方法1功能
|
||
* - method2() - 方法2功能
|
||
*
|
||
* 使用场景:
|
||
* - 场景描述
|
||
*/
|
||
@Injectable()
|
||
export class ExampleService {
|
||
// 类实现
|
||
}
|
||
```
|
||
|
||
### 🔧 方法注释(三级标准)
|
||
|
||
**必须包含的信息:**
|
||
|
||
```typescript
|
||
/**
|
||
* 用户登录验证
|
||
*
|
||
* 业务逻辑:
|
||
* 1. 验证用户名或邮箱格式
|
||
* 2. 查找用户记录
|
||
* 3. 验证密码哈希值
|
||
* 4. 检查用户状态是否允许登录
|
||
* 5. 记录登录日志
|
||
* 6. 返回认证结果
|
||
*
|
||
* @param loginRequest 登录请求数据
|
||
* @returns 认证结果,包含用户信息和认证状态
|
||
* @throws UnauthorizedException 用户名或密码错误时
|
||
* @throws ForbiddenException 用户状态不允许登录时
|
||
*
|
||
* @example
|
||
* ```typescript
|
||
* const result = await loginService.validateUser({
|
||
* identifier: 'user@example.com',
|
||
* password: 'password123'
|
||
* });
|
||
* ```
|
||
*/
|
||
async validateUser(loginRequest: LoginRequest): Promise<AuthResult> {
|
||
// 实现代码
|
||
}
|
||
```
|
||
|
||
### 📝 修改记录规范
|
||
|
||
**修改类型定义:**
|
||
- `代码规范优化` - 命名规范、注释规范、代码清理等
|
||
- `功能新增` - 添加新的功能或方法
|
||
- `功能修改` - 修改现有功能的实现
|
||
- `Bug修复` - 修复代码缺陷
|
||
- `性能优化` - 提升代码性能
|
||
- `重构` - 代码结构调整但功能不变
|
||
|
||
**格式要求:**
|
||
```typescript
|
||
/**
|
||
* 最近修改:
|
||
* - 2024-01-07: 代码规范优化 - 清理未使用的导入 (修改者: 张三)
|
||
* - 2024-01-06: Bug修复 - 修复邮箱验证逻辑错误 (修改者: 李四)
|
||
* - 2024-01-05: 功能新增 - 添加用户验证码登录功能 (修改者: 王五)
|
||
*
|
||
* @version 1.0.1
|
||
* @lastModified 2024-01-07
|
||
*/
|
||
```
|
||
|
||
**作者字段处理规范:**
|
||
- **保留原则**:@author字段中的人名必须保留,不得随意修改
|
||
- **AI标识替换**:只有当@author字段包含AI标识(如kiro、ChatGPT、Claude、AI等)时,才可以替换为实际的修改者名称
|
||
- **判断标准**:
|
||
- ✅ 可以替换:`@author kiro` → `@author 张三`
|
||
- ✅ 可以替换:`@author ChatGPT` → `@author 李四`
|
||
- ❌ 不可替换:`@author 王五` → 必须保留为 `@author 王五`
|
||
- ❌ 不可替换:`@author John Smith` → 必须保留为 `@author John Smith`
|
||
|
||
**修改记录更新要求:**
|
||
- **必须添加**:每次修改文件后,必须在"最近修改"部分添加新的修改记录
|
||
- **信息完整**:包含修改日期、修改类型、修改内容、修改者姓名
|
||
- **时间更新**:同时更新@lastModified字段为当前修改时间
|
||
- **版本递增**:根据修改类型适当递增版本号
|
||
|
||
**版本号递增规则:**
|
||
- 代码规范优化、Bug修复 → 修订版本 +1 (1.0.0 → 1.0.1)
|
||
- 功能新增、功能修改 → 次版本 +1 (1.0.1 → 1.1.0)
|
||
- 重构、架构变更 → 主版本 +1 (1.1.0 → 2.0.0)
|
||
|
||
---
|
||
|
||
## 3️⃣ 代码质量检查
|
||
|
||
### 🧹 导入清理
|
||
|
||
**清理未使用的导入:**
|
||
|
||
```typescript
|
||
// ✅ 正确:只导入使用的模块
|
||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||
import { User } from './user.entity';
|
||
|
||
// ❌ 错误:导入未使用的模块
|
||
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
|
||
import { User, Admin } from './user.entity';
|
||
import * as crypto from 'crypto'; // 未使用
|
||
```
|
||
|
||
### 📊 常量定义检查
|
||
|
||
```typescript
|
||
// ✅ 正确:使用全大写+下划线
|
||
const SALT_ROUNDS = 10;
|
||
const MAX_LOGIN_ATTEMPTS = 5;
|
||
const DEFAULT_PAGE_SIZE = 20;
|
||
|
||
// ❌ 错误:使用小驼峰
|
||
const saltRounds = 10;
|
||
const maxLoginAttempts = 5;
|
||
```
|
||
|
||
### 🗑️ 未使用代码清理
|
||
|
||
```typescript
|
||
// ❌ 需要删除:未使用的私有方法
|
||
private generateVerificationCode(): string {
|
||
// 如果这个方法没有被调用,应该删除
|
||
}
|
||
|
||
// ❌ 需要删除:未使用的变量
|
||
const unusedVariable = 'test';
|
||
```
|
||
|
||
### 📏 方法长度检查
|
||
|
||
```typescript
|
||
// ✅ 正确:方法长度合理(建议不超过50行)
|
||
async createUser(userData: CreateUserDto): Promise<User> {
|
||
// 简洁的实现
|
||
}
|
||
|
||
// ❌ 错误:方法过长,需要拆分
|
||
async complexMethod() {
|
||
// 超过50行的复杂逻辑,应该拆分成多个小方法
|
||
}
|
||
```
|
||
---
|
||
|
||
## 4️⃣ 架构分层检查
|
||
|
||
### 🏗️ 架构层级识别
|
||
|
||
**项目采用分层架构:**
|
||
|
||
```
|
||
src/
|
||
├── core/ # Core层:技术实现层
|
||
│ ├── db/ # 数据访问
|
||
│ ├── redis/ # 缓存服务
|
||
│ └── utils/ # 工具服务
|
||
├── business/ # Business层:业务逻辑层
|
||
│ ├── auth/ # 认证业务
|
||
│ ├── users/ # 用户业务
|
||
│ └── admin/ # 管理业务
|
||
└── common/ # 公共层:通用组件
|
||
```
|
||
|
||
### 🔧 Core层规范
|
||
|
||
**职责:专注技术实现,不包含业务逻辑**
|
||
|
||
#### 命名规范
|
||
- **业务支撑模块**:使用`_core`后缀(如`users_core`、`login_core`)
|
||
- **底层工具模块**:不使用`_core`后缀(如`redis`、`logger`)
|
||
|
||
```typescript
|
||
✅ 正确示例:
|
||
src/core/db/users_core/ # 为business/users提供数据层支撑
|
||
src/core/login_core/ # 为business/auth提供登录技术实现
|
||
src/core/redis/ # 纯Redis技术封装
|
||
src/core/utils/logger/ # 纯日志工具
|
||
|
||
❌ 错误示例:
|
||
src/core/db/users/ # 应该是users_core
|
||
src/core/redis_core/ # 应该是redis
|
||
```
|
||
|
||
#### 技术实现示例
|
||
```typescript
|
||
// ✅ 正确:Core层专注技术实现
|
||
@Injectable()
|
||
export class RedisService {
|
||
/**
|
||
* 设置缓存数据
|
||
*
|
||
* 技术实现:
|
||
* 1. 验证key格式
|
||
* 2. 序列化数据
|
||
* 3. 设置过期时间
|
||
* 4. 处理连接异常
|
||
*/
|
||
async set(key: string, value: any, ttl?: number): Promise<void> {
|
||
// 专注Redis技术实现细节
|
||
}
|
||
}
|
||
|
||
// ❌ 错误:Core层包含业务逻辑
|
||
@Injectable()
|
||
export class RedisService {
|
||
async setUserSession(userId: string, sessionData: any): Promise<void> {
|
||
// 错误:包含了用户会话的业务概念
|
||
}
|
||
}
|
||
```
|
||
|
||
#### 依赖关系
|
||
- ✅ 允许:导入其他Core层模块
|
||
- ✅ 允许:导入第三方技术库
|
||
- ✅ 允许:导入Node.js内置模块
|
||
- ❌ 禁止:导入Business层模块
|
||
- ❌ 禁止:包含具体业务概念的命名
|
||
|
||
### 💼 Business层规范
|
||
|
||
**职责:专注业务逻辑实现,不关心底层技术细节**
|
||
|
||
#### 业务逻辑完备性
|
||
```typescript
|
||
// ✅ 正确:完整的业务逻辑
|
||
@Injectable()
|
||
export class UserBusinessService {
|
||
/**
|
||
* 用户注册业务流程
|
||
*
|
||
* 业务逻辑:
|
||
* 1. 验证用户信息完整性
|
||
* 2. 检查用户名/邮箱是否已存在
|
||
* 3. 验证邮箱格式和域名白名单
|
||
* 4. 生成用户唯一标识
|
||
* 5. 设置默认用户权限
|
||
* 6. 发送欢迎邮件
|
||
* 7. 记录注册日志
|
||
* 8. 返回注册结果
|
||
*/
|
||
async registerUser(registerData: RegisterUserDto): Promise<UserResult> {
|
||
// 完整的业务逻辑实现
|
||
}
|
||
}
|
||
|
||
// ❌ 错误:业务逻辑不完整
|
||
@Injectable()
|
||
export class UserBusinessService {
|
||
async registerUser(registerData: RegisterUserDto): Promise<User> {
|
||
// 只是简单调用数据库保存,缺少业务验证和流程
|
||
return this.userRepository.save(registerData);
|
||
}
|
||
}
|
||
```
|
||
|
||
#### 依赖关系
|
||
- ✅ 允许:导入对应的Core层业务支撑模块
|
||
- ✅ 允许:导入Core层通用工具模块
|
||
- ✅ 允许:导入其他Business层模块(谨慎使用)
|
||
- ✅ 允许:导入第三方业务库
|
||
- ❌ 禁止:直接导入底层技术实现(如数据库连接、Redis客户端等)
|
||
- ❌ 禁止:包含技术实现细节
|
||
|
||
#### 正确的分层实现
|
||
```typescript
|
||
// ✅ 正确:Business层调用Core层服务
|
||
@Injectable()
|
||
export class UserBusinessService {
|
||
constructor(
|
||
private readonly userCoreService: UserCoreService,
|
||
private readonly cacheService: CacheService,
|
||
private readonly emailService: EmailService,
|
||
) {}
|
||
|
||
async createUser(userData: CreateUserDto): Promise<User> {
|
||
// 业务验证
|
||
await this.validateUserBusinessRules(userData);
|
||
|
||
// 调用Core层服务
|
||
const user = await this.userCoreService.create(userData);
|
||
await this.cacheService.set(`user:${user.id}`, user);
|
||
await this.emailService.sendWelcomeEmail(user.email);
|
||
|
||
return user;
|
||
}
|
||
}
|
||
```
|
||
|
||
### 🔍 常见架构违规
|
||
|
||
#### Business层违规示例
|
||
```typescript
|
||
// ❌ 错误:Business层包含技术实现细节
|
||
@Injectable()
|
||
export class UserBusinessService {
|
||
async createUser(userData: CreateUserDto): Promise<User> {
|
||
// 违规:直接操作Redis连接
|
||
const redis = new Redis({ host: 'localhost', port: 6379 });
|
||
await redis.set(`user:${userData.id}`, JSON.stringify(userData));
|
||
|
||
// 违规:直接写SQL语句
|
||
const sql = 'INSERT INTO users (name, email) VALUES (?, ?)';
|
||
await this.database.query(sql, [userData.name, userData.email]);
|
||
}
|
||
}
|
||
```
|
||
|
||
#### Core层违规示例
|
||
```typescript
|
||
// ❌ 错误:Core层包含业务逻辑
|
||
@Injectable()
|
||
export class DatabaseService {
|
||
async saveUser(userData: CreateUserDto): Promise<User> {
|
||
// 违规:包含用户注册的业务验证
|
||
if (userData.age < 18) {
|
||
throw new BadRequestException('用户年龄必须大于18岁');
|
||
}
|
||
|
||
// 违规:包含业务规则
|
||
if (userData.email.endsWith('@competitor.com')) {
|
||
throw new ForbiddenException('不允许竞争对手注册');
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 5️⃣ 测试覆盖检查
|
||
|
||
### 📋 测试文件存在性
|
||
|
||
**规则:每个Service都必须有对应的.spec.ts测试文件**
|
||
|
||
```typescript
|
||
// ✅ 正确:Service与测试文件一一对应
|
||
src/core/db/users/users.service.ts
|
||
src/core/db/users/users.service.spec.ts
|
||
|
||
src/core/db/users/users_memory.service.ts
|
||
src/core/db/users/users_memory.service.spec.ts
|
||
|
||
// ❌ 错误:缺少测试文件
|
||
src/core/login_core/login_core.service.ts
|
||
# 缺少:src/core/login_core/login_core.service.spec.ts
|
||
```
|
||
|
||
### 🎯 测试用例覆盖完整性
|
||
|
||
**要求:测试文件必须覆盖Service中的所有公共方法**
|
||
|
||
```typescript
|
||
// 示例Service
|
||
@Injectable()
|
||
export class UserService {
|
||
async createUser(userData: CreateUserDto): Promise<User> { }
|
||
async findUserById(id: string): Promise<User> { }
|
||
async updateUser(id: string, updateData: UpdateUserDto): Promise<User> { }
|
||
async deleteUser(id: string): Promise<void> { }
|
||
async findUsersByStatus(status: UserStatus): Promise<User[]> { }
|
||
}
|
||
|
||
// ✅ 正确:完整的测试覆盖
|
||
describe('UserService', () => {
|
||
// 每个公共方法都有对应的测试
|
||
describe('createUser', () => {
|
||
it('should create user successfully', () => { });
|
||
it('should throw error when email already exists', () => { });
|
||
it('should throw error when required fields missing', () => { });
|
||
});
|
||
|
||
describe('findUserById', () => {
|
||
it('should return user when found', () => { });
|
||
it('should throw NotFoundException when user not found', () => { });
|
||
it('should throw error when id is invalid', () => { });
|
||
});
|
||
|
||
// ... 其他方法的测试
|
||
});
|
||
```
|
||
|
||
### 🧪 测试场景真实性
|
||
|
||
**要求:每个方法必须测试正常情况、异常情况和边界情况**
|
||
|
||
```typescript
|
||
// ✅ 正确:完整的测试场景
|
||
describe('createUser', () => {
|
||
// 正常情况
|
||
it('should create user with valid data', async () => {
|
||
const userData = { name: 'John', email: 'john@example.com' };
|
||
const result = await service.createUser(userData);
|
||
expect(result).toBeDefined();
|
||
expect(result.name).toBe('John');
|
||
});
|
||
|
||
// 异常情况
|
||
it('should throw ConflictException when email already exists', async () => {
|
||
const userData = { name: 'John', email: 'existing@example.com' };
|
||
await expect(service.createUser(userData)).rejects.toThrow(ConflictException);
|
||
});
|
||
|
||
// 边界情况
|
||
it('should handle empty name gracefully', async () => {
|
||
const userData = { name: '', email: 'test@example.com' };
|
||
await expect(service.createUser(userData)).rejects.toThrow(BadRequestException);
|
||
});
|
||
});
|
||
```
|
||
|
||
### 🏗️ 测试代码质量
|
||
|
||
**要求:测试代码必须清晰、可维护、真实有效**
|
||
|
||
```typescript
|
||
// ✅ 正确:高质量的测试代码
|
||
describe('UserService', () => {
|
||
let service: UserService;
|
||
let mockRepository: jest.Mocked<Repository<User>>;
|
||
|
||
beforeEach(async () => {
|
||
const mockRepo = {
|
||
save: jest.fn(),
|
||
findOne: jest.fn(),
|
||
find: jest.fn(),
|
||
delete: jest.fn(),
|
||
};
|
||
|
||
const module: TestingModule = await Test.createTestingModule({
|
||
providers: [
|
||
UserService,
|
||
{ provide: getRepositoryToken(User), useValue: mockRepo },
|
||
],
|
||
}).compile();
|
||
|
||
service = module.get<UserService>(UserService);
|
||
mockRepository = module.get(getRepositoryToken(User));
|
||
});
|
||
|
||
afterEach(() => {
|
||
jest.clearAllMocks();
|
||
});
|
||
|
||
describe('findUserById', () => {
|
||
it('should return user when found', async () => {
|
||
// Arrange
|
||
const userId = '123';
|
||
const expectedUser = { id: userId, name: 'John', email: 'john@example.com' };
|
||
mockRepository.findOne.mockResolvedValue(expectedUser);
|
||
|
||
// Act
|
||
const result = await service.findUserById(userId);
|
||
|
||
// Assert
|
||
expect(result).toEqual(expectedUser);
|
||
expect(mockRepository.findOne).toHaveBeenCalledWith({ where: { id: userId } });
|
||
});
|
||
});
|
||
});
|
||
```
|
||
|
||
### 🔗 集成测试
|
||
|
||
**要求:复杂Service需要集成测试文件(.integration.spec.ts)**
|
||
|
||
```typescript
|
||
// ✅ 正确:提供集成测试
|
||
src/core/db/users/users.service.ts
|
||
src/core/db/users/users.service.spec.ts # 单元测试
|
||
src/core/db/users/users.integration.spec.ts # 集成测试
|
||
```
|
||
|
||
### ⚡ 测试执行
|
||
|
||
**推荐的测试命令:**
|
||
|
||
```bash
|
||
# 针对特定文件夹的测试(推荐)- 排除集成测试
|
||
npx jest src/core/db/users --testPathIgnorePatterns="integration.spec.ts"
|
||
|
||
# 针对特定文件的测试
|
||
npx jest src/core/db/users/users.service.spec.ts
|
||
|
||
# 带覆盖率的测试执行
|
||
npx jest src/core/db/users --coverage --testPathIgnorePatterns="integration.spec.ts"
|
||
```
|
||
---
|
||
|
||
## 6️⃣ 功能文档生成
|
||
|
||
### 📚 README文档结构
|
||
|
||
**要求:每个功能模块文件夹都必须有README.md文档**
|
||
|
||
#### 1. 模块概述
|
||
```markdown
|
||
# [模块名称] [中文描述]
|
||
|
||
[模块名称] 是 [一段话总结文件夹的整体功能和作用,说明其在项目中的定位和价值]。
|
||
```
|
||
|
||
#### 2. 对外提供的接口
|
||
```markdown
|
||
## 用户数据操作
|
||
|
||
### create()
|
||
创建新用户记录,支持数据验证和唯一性检查。
|
||
|
||
### findByEmail()
|
||
根据邮箱地址查询用户,用于登录验证和账户找回。
|
||
|
||
### updateUserStatus()
|
||
更新用户状态,支持激活、禁用、待验证等状态切换。
|
||
```
|
||
|
||
#### 3. 使用的项目内部依赖
|
||
```markdown
|
||
## 使用的项目内部依赖
|
||
|
||
### UserStatus (来自 business/user-mgmt/enums/user-status.enum)
|
||
用户状态枚举,定义用户的激活、禁用、待验证等状态值。
|
||
|
||
### CreateUserDto (本模块)
|
||
用户创建数据传输对象,提供完整的数据验证规则和类型定义。
|
||
|
||
### LoggerService (来自 core/utils/logger)
|
||
日志服务,用于记录用户操作和系统事件。
|
||
```
|
||
|
||
#### 4. 核心特性
|
||
```markdown
|
||
## 核心特性
|
||
|
||
### 双存储模式支持
|
||
- 数据库模式:使用TypeORM连接MySQL,适用于生产环境
|
||
- 内存模式:使用Map存储,适用于开发测试和故障降级
|
||
- 动态模块配置:通过UsersModule.forDatabase()和forMemory()灵活切换
|
||
|
||
### 数据完整性保障
|
||
- 唯一性约束检查:用户名、邮箱、手机号、GitHub ID
|
||
- 数据验证:使用class-validator进行输入验证
|
||
- 事务支持:批量操作支持回滚机制
|
||
|
||
### 性能优化
|
||
- 查询优化:使用索引和查询缓存
|
||
- 批量操作:支持批量创建和更新
|
||
- 内存缓存:热点数据缓存机制
|
||
```
|
||
|
||
#### 5. 潜在风险
|
||
```markdown
|
||
## 潜在风险
|
||
|
||
### 内存模式数据丢失
|
||
- 内存存储在应用重启后数据会丢失
|
||
- 不适用于生产环境的持久化需求
|
||
- 建议仅在开发测试环境使用
|
||
|
||
### 并发操作风险
|
||
- 内存模式的ID生成锁机制相对简单
|
||
- 高并发场景可能存在性能瓶颈
|
||
- 建议在生产环境使用数据库模式
|
||
|
||
### 数据一致性风险
|
||
- 跨模块操作时可能存在数据不一致
|
||
- 需要注意事务边界的设计
|
||
- 建议使用分布式事务或补偿机制
|
||
```
|
||
|
||
### 📝 文档质量要求
|
||
|
||
#### 内容质量标准
|
||
- **准确性**:所有信息必须与代码实现一致
|
||
- **完整性**:覆盖所有公共接口和重要功能
|
||
- **简洁性**:每个说明控制在一句话内,突出核心要点
|
||
- **实用性**:提供对开发者有价值的信息和建议
|
||
|
||
#### 语言表达规范
|
||
- 使用中文进行描述,专业术语可保留英文
|
||
- 语言简洁明了,避免冗长的句子
|
||
- 统一术语使用,保持前后一致
|
||
- 避免主观评价,客观描述功能和特性
|
||
|
||
---
|
||
|
||
## 🛠️ 实用工具和技巧
|
||
|
||
### 📋 检查清单
|
||
|
||
#### 命名规范检查清单
|
||
- [ ] 文件名使用snake_case(下划线分隔)
|
||
- [ ] 变量和函数使用camelCase(小驼峰)
|
||
- [ ] 类和接口使用PascalCase(大驼峰)
|
||
- [ ] 常量使用SCREAMING_SNAKE_CASE(全大写+下划线)
|
||
- [ ] 路由使用kebab-case(短横线分隔)
|
||
- [ ] 避免过度嵌套的文件夹结构
|
||
- [ ] Core层业务支撑模块使用_core后缀
|
||
|
||
#### 注释规范检查清单
|
||
- [ ] 文件头注释包含功能描述、职责分离、修改记录
|
||
- [ ] 类注释包含职责、主要方法、使用场景
|
||
- [ ] 方法注释包含业务逻辑、参数说明、返回值、异常、示例
|
||
- [ ] 修改记录使用正确的日期和修改者信息
|
||
- [ ] 版本号按规则递增
|
||
- [ ] @author字段正确处理(AI标识替换为实际作者)
|
||
|
||
#### 代码质量检查清单
|
||
- [ ] 清理所有未使用的导入
|
||
- [ ] 清理所有未使用的变量和方法
|
||
- [ ] 常量使用正确的命名规范
|
||
- [ ] 方法长度控制在合理范围内(建议不超过50行)
|
||
- [ ] 避免代码重复
|
||
|
||
#### 架构分层检查清单
|
||
- [ ] Core层专注技术实现,不包含业务逻辑
|
||
- [ ] Business层专注业务逻辑,不包含技术实现细节
|
||
- [ ] 依赖关系符合分层架构要求
|
||
- [ ] 模块职责清晰,边界明确
|
||
|
||
#### 测试覆盖检查清单
|
||
- [ ] 每个Service都有对应的.spec.ts测试文件
|
||
- [ ] 所有公共方法都有测试覆盖
|
||
- [ ] 测试覆盖正常情况、异常情况、边界情况
|
||
- [ ] 测试代码质量高,真实有效
|
||
- [ ] 复杂Service提供集成测试
|
||
- [ ] 测试能够成功执行
|
||
|
||
#### 功能文档检查清单
|
||
- [ ] 每个功能模块都有README.md文档
|
||
- [ ] 文档包含模块概述、对外接口、内部依赖、核心特性、潜在风险
|
||
- [ ] 所有公共接口都有准确的功能描述
|
||
- [ ] 文档内容与代码实现一致
|
||
- [ ] 语言表达简洁明了
|
||
|
||
### 🔧 常用命令
|
||
|
||
#### 测试相关命令
|
||
```bash
|
||
# 运行特定文件夹的单元测试
|
||
npx jest src/core/db/users --testPathIgnorePatterns="integration.spec.ts"
|
||
|
||
# 运行特定文件的测试
|
||
npx jest src/core/db/users/users.service.spec.ts
|
||
|
||
# 运行测试并生成覆盖率报告
|
||
npx jest src/core/db/users --coverage
|
||
|
||
# 静默模式运行测试
|
||
npx jest src/core/db/users --silent
|
||
```
|
||
|
||
#### 代码检查命令
|
||
```bash
|
||
# TypeScript类型检查
|
||
npx tsc --noEmit
|
||
|
||
# ESLint代码检查
|
||
npx eslint src/**/*.ts
|
||
|
||
# Prettier代码格式化
|
||
npx prettier --write src/**/*.ts
|
||
```
|
||
|
||
### 🚨 常见错误和解决方案
|
||
|
||
#### 命名规范常见错误
|
||
1. **短横线命名错误**
|
||
- 错误:`base-users.service.ts`
|
||
- 正确:`base_users.service.ts`
|
||
- 解决:统一使用下划线分隔
|
||
|
||
2. **常量命名错误**
|
||
- 错误:`const saltRounds = 10;`
|
||
- 正确:`const SALT_ROUNDS = 10;`
|
||
- 解决:常量使用全大写+下划线
|
||
|
||
#### 架构分层常见错误
|
||
1. **Business层包含技术实现**
|
||
- 错误:直接操作数据库连接
|
||
- 正确:调用Core层服务
|
||
- 解决:通过依赖注入使用Core层服务
|
||
|
||
2. **Core层包含业务逻辑**
|
||
- 错误:在数据层进行业务验证
|
||
- 正确:只处理技术实现
|
||
- 解决:将业务逻辑移到Business层
|
||
|
||
#### 测试覆盖常见错误
|
||
1. **测试文件缺失**
|
||
- 错误:Service没有对应的.spec.ts文件
|
||
- 解决:为每个Service创建测试文件
|
||
|
||
2. **测试场景不完整**
|
||
- 错误:只测试正常情况
|
||
- 正确:测试正常、异常、边界情况
|
||
- 解决:补充异常和边界情况的测试用例
|
||
|
||
---
|
||
|
||
## 📈 最佳实践建议
|
||
|
||
### 🎯 开发流程建议
|
||
|
||
1. **编码前**:明确模块职责和架构定位
|
||
2. **编码中**:遵循命名规范和注释规范
|
||
3. **编码后**:进行代码质量检查和测试覆盖
|
||
4. **提交前**:生成或更新功能文档
|
||
|
||
### 🔄 持续改进
|
||
|
||
1. **定期检查**:建议每周进行一次全面的代码规范检查
|
||
2. **团队协作**:通过Code Review确保规范执行
|
||
3. **工具辅助**:使用ESLint、Prettier等工具自动化检查
|
||
4. **文档维护**:及时更新文档,保持与代码同步
|
||
|
||
### 📊 质量指标
|
||
|
||
1. **命名规范达标率**:目标100%
|
||
2. **注释覆盖率**:文件头、类、公共方法100%覆盖
|
||
3. **测试覆盖率**:单元测试覆盖率>90%
|
||
4. **文档完整性**:每个功能模块都有README文档
|
||
|
||
---
|
||
|
||
## 🤝 团队协作
|
||
|
||
### 👥 角色职责
|
||
|
||
- **开发者**:遵循规范进行开发,自检代码质量
|
||
- **Code Reviewer**:检查代码是否符合规范要求
|
||
- **架构师**:制定和维护架构分层规范
|
||
- **测试工程师**:确保测试覆盖率和测试质量
|
||
|
||
### 📋 Review检查点
|
||
|
||
1. **命名规范**:文件、变量、函数、类的命名是否符合规范
|
||
2. **注释完整性**:文件头、类、方法注释是否完整准确
|
||
3. **代码质量**:是否有未使用的代码,常量定义是否规范
|
||
4. **架构合规性**:是否符合分层架构要求
|
||
5. **测试覆盖**:是否有对应的测试文件和完整的测试用例
|
||
6. **文档同步**:README文档是否与代码实现一致
|
||
|
||
### 🛡️ 质量保障
|
||
|
||
1. **自动化检查**:集成ESLint、Prettier、Jest等工具
|
||
2. **CI/CD集成**:在构建流程中加入代码规范检查
|
||
3. **定期审计**:定期进行代码规范审计和改进
|
||
4. **培训推广**:定期组织团队培训,提高规范意识
|
||
|
||
---
|
||
|
||
## 📞 支持和反馈
|
||
|
||
如果在使用过程中遇到问题或有改进建议,请:
|
||
|
||
1. 查阅本文档的相关章节
|
||
2. 参考常见错误和解决方案
|
||
3. 向团队架构师或技术负责人咨询
|
||
4. 提交改进建议,持续优化规范
|
||
|
||
**记住:代码规范不是束缚,而是提高代码质量和团队协作效率的有力工具!** 🚀 |