feat(types): 新增共享类型中心,包含用户、产品、订单等核心领域类型 fix(types): 修复类型定义错误,统一各模块类型引用 style(types): 优化类型文件格式和注释 docs(types): 更新类型文档和变更日志 test(types): 添加类型测试用例 build(types): 配置类型共享路径 chore(types): 清理重复类型定义文件
343 lines
7.7 KiB
Markdown
343 lines
7.7 KiB
Markdown
# AI 开发快速参考卡片(AI Development Quick Reference Card)
|
||
|
||
> **模块**: 05_AI - AI 开发快速参考
|
||
> **更新日期**: 2026-03-20
|
||
> **用途**: AI 开发时快速查阅的关键约束和规范
|
||
|
||
---
|
||
|
||
## 🔴 硬性约束(必须遵守)
|
||
|
||
### 1. TypeScript 类型安全
|
||
|
||
| 约束 | 说明 | 示例 |
|
||
|------|------|------|
|
||
| ❌ **禁止 any** | 使用 `unknown` + 类型守卫 | `function handle(data: unknown)` |
|
||
| ✅ **函数返回类型** | 所有函数必须声明返回类型 | `function getUser(): User` |
|
||
| ✅ **API 类型定义** | 所有 API 必须定义类型 | `axios.get<ApiResponse<User>>('/api')` |
|
||
| ✅ **Schema 驱动** | 类型从 Schema 推导 | `type User = z.infer<typeof UserSchema>` |
|
||
|
||
### 2. 逻辑集中化
|
||
|
||
| 层级 | 职责 | 禁止行为 |
|
||
|------|------|----------|
|
||
| **Controller** | 请求/响应 + 权限校验 | ❌ 业务逻辑 |
|
||
| **Service** | 业务逻辑 + 状态流转 | ✅ 核心逻辑 |
|
||
| **Repository** | 数据库 CRUD | ❌ 业务逻辑 |
|
||
|
||
### 3. 数据安全
|
||
|
||
| 约束 | 说明 |
|
||
|------|------|
|
||
| **表前缀** | 所有表必须以 `cf_` 开头 |
|
||
| **金额字段** | 必须使用 `decimal(10,2)` |
|
||
| **五元组** | tenantId, shopId, taskId, traceId, businessType |
|
||
|
||
### 4. 业务红线
|
||
|
||
| 场景 | 规则 |
|
||
|------|------|
|
||
| **B2B 利润率** | < 15% → 禁止报价 |
|
||
| **B2C 利润率** | < 20% → 触发风控预警 |
|
||
| **决策流程** | SUGGESTED → PENDING_REVIEW → EXECUTED/REJECTED |
|
||
|
||
---
|
||
|
||
## 🟡 开发流程
|
||
|
||
### 标准开发顺序
|
||
|
||
```
|
||
1. Service(业务逻辑)
|
||
↓
|
||
2. Repository(数据访问)
|
||
↓
|
||
3. Controller(接口层)
|
||
↓
|
||
4. Frontend(前端实现)
|
||
↓
|
||
5. Test(测试用例)
|
||
```
|
||
|
||
### 类型转换流程
|
||
|
||
```
|
||
API 返回数据
|
||
↓
|
||
Schema 验证(zod)
|
||
↓
|
||
DTO 转换
|
||
↓
|
||
Domain 模型
|
||
```
|
||
|
||
---
|
||
|
||
## 🟢 代码模板
|
||
|
||
### Service 层模板
|
||
|
||
```typescript
|
||
import { z } from 'zod'
|
||
import { User, UserDTO } from '@/types'
|
||
import { UserSchema } from '@/types/domain/User.schema'
|
||
|
||
export class UserService {
|
||
constructor(
|
||
private readonly userRepository: UserRepository
|
||
) {}
|
||
|
||
/**
|
||
* 创建用户
|
||
* [BE-U001] 用户创建服务
|
||
*/
|
||
async createUser(request: CreateUserRequest): Promise<UserDTO> {
|
||
// 1. 验证请求数据
|
||
const validatedRequest = CreateUserRequestSchema.parse(request)
|
||
|
||
// 2. 创建领域模型
|
||
const user = UserSchema.parse({
|
||
id: crypto.randomUUID(),
|
||
username: validatedRequest.username,
|
||
email: validatedRequest.email,
|
||
role: validatedRequest.role,
|
||
status: 'ACTIVE',
|
||
createdAt: new Date(),
|
||
updatedAt: new Date()
|
||
})
|
||
|
||
// 3. 保存到数据库
|
||
const savedUser = await this.userRepository.create(user)
|
||
|
||
// 4. 转换为 DTO
|
||
return toUserDTO(savedUser)
|
||
}
|
||
}
|
||
```
|
||
|
||
### Controller 层模板
|
||
|
||
```typescript
|
||
import { Request, Response } from 'express'
|
||
import { CreateUserRequest, CreateUserResponse } from '@/types'
|
||
import { createSuccessResponse, createErrorResponse } from '@/types/shared/Response'
|
||
|
||
export class UserController {
|
||
constructor(private readonly userService: UserService) {}
|
||
|
||
async createUser(req: Request, res: Response): Promise<void> {
|
||
try {
|
||
const request: CreateUserRequest = CreateUserRequestSchema.parse(req.body)
|
||
const userDTO = await this.userService.createUser(request)
|
||
|
||
const response = createSuccessResponse({
|
||
id: userDTO.id,
|
||
username: userDTO.username,
|
||
email: userDTO.email,
|
||
role: userDTO.role,
|
||
createdAt: userDTO.createdAt
|
||
})
|
||
|
||
res.json(response)
|
||
} catch (error) {
|
||
const response = createErrorResponse(
|
||
'INTERNAL_ERROR',
|
||
error instanceof Error ? error.message : 'Unknown error'
|
||
)
|
||
res.status(500).json(response)
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
### Schema 定义模板
|
||
|
||
```typescript
|
||
import { z } from 'zod'
|
||
|
||
export const UserSchema = z.object({
|
||
id: z.string().uuid(),
|
||
username: z.string().min(3).max(50),
|
||
email: z.string().email(),
|
||
role: z.enum(['ADMIN', 'MANAGER', 'OPERATOR']),
|
||
status: z.enum(['ACTIVE', 'INACTIVE']).default('ACTIVE'),
|
||
createdAt: z.date(),
|
||
updatedAt: z.date()
|
||
})
|
||
|
||
export type User = z.infer<typeof UserSchema>
|
||
```
|
||
|
||
---
|
||
|
||
## 🔵 常见错误对比
|
||
|
||
### ❌ 错误示例 vs ✅ 正确示例
|
||
|
||
#### 1. 类型定义
|
||
|
||
```typescript
|
||
// ❌ 错误:使用 any
|
||
function handle(data: any) {
|
||
return data.name
|
||
}
|
||
|
||
// ✅ 正确:使用 unknown + 类型守卫
|
||
function handle(data: unknown) {
|
||
if (typeof data === 'object' && data !== null && 'name' in data) {
|
||
return (data as { name: string }).name
|
||
}
|
||
throw new Error('Invalid data')
|
||
}
|
||
```
|
||
|
||
#### 2. 函数返回类型
|
||
|
||
```typescript
|
||
// ❌ 错误:未声明返回类型
|
||
function getUser(userId: string) {
|
||
return userRepository.findById(userId)
|
||
}
|
||
|
||
// ✅ 正确:声明返回类型
|
||
function getUser(userId: string): Promise<User | null> {
|
||
return userRepository.findById(userId)
|
||
}
|
||
```
|
||
|
||
#### 3. API 调用
|
||
|
||
```typescript
|
||
// ❌ 错误:未定义类型
|
||
const response = await axios.get('/api/users')
|
||
|
||
// ✅ 正确:定义类型
|
||
const response = await axios.get<ApiResponse<User[]>>('/api/users')
|
||
const users = response.data.data
|
||
```
|
||
|
||
#### 4. 业务逻辑位置
|
||
|
||
```typescript
|
||
// ❌ 错误:Controller 中写业务逻辑
|
||
async createUser(req: Request, res: Response) {
|
||
const { username, email } = req.body
|
||
if (!username || !email) {
|
||
return res.status(400).json({ error: 'Missing fields' })
|
||
}
|
||
const user = await this.userRepository.create({ username, email })
|
||
res.json(user)
|
||
}
|
||
|
||
// ✅ 正确:Controller 只负责请求/响应
|
||
async createUser(req: Request, res: Response) {
|
||
try {
|
||
const userDTO = await this.userService.createUser(req.body)
|
||
res.json(createSuccessResponse(userDTO))
|
||
} catch (error) {
|
||
res.status(500).json(createErrorResponse('ERROR', error.message))
|
||
}
|
||
}
|
||
```
|
||
|
||
#### 5. 类型定义方式
|
||
|
||
```typescript
|
||
// ❌ 错误:手动定义类型
|
||
interface User {
|
||
id: string
|
||
name: string
|
||
email: string
|
||
}
|
||
|
||
// ✅ 正确:从 Schema 推导类型
|
||
const UserSchema = z.object({
|
||
id: z.string().uuid(),
|
||
name: z.string(),
|
||
email: z.string().email()
|
||
})
|
||
|
||
type User = z.infer<typeof UserSchema>
|
||
```
|
||
|
||
---
|
||
|
||
## 🟣 检查清单
|
||
|
||
### 开发前检查
|
||
|
||
- [ ] 已阅读相关业务文档
|
||
- [ ] 已理解状态机流转
|
||
- [ ] 已确认任务依赖关系
|
||
- [ ] 已声明文件占用
|
||
|
||
### 开发中检查
|
||
|
||
- [ ] 所有函数已声明返回类型
|
||
- [ ] 所有 API 调用已定义类型
|
||
- [ ] 业务逻辑在 Service 层
|
||
- [ ] 类型从 Schema 推导
|
||
- [ ] 所有类型从 `/types` 导入
|
||
|
||
### 提交前检查
|
||
|
||
- [ ] `tsc --noEmit` 无错误
|
||
- [ ] `eslint` 无错误
|
||
- [ ] 单元测试通过
|
||
- [ ] 五元组已填写
|
||
- [ ] JSDoc 注释完整
|
||
|
||
---
|
||
|
||
## 🟤 快速导航
|
||
|
||
| 文档 | 路径 |
|
||
|------|------|
|
||
| **TypeScript 编译规约** | `docs/01_Architecture/13_TypeScript_Standards.md` |
|
||
| **代码质量规范** | `docs/01_Architecture/14_Code_Quality_Standards.md` |
|
||
| **Schema 驱动开发** | `docs/01_Architecture/15_Schema_Driven_Development.md` |
|
||
| **统一类型管理** | `docs/01_Architecture/16_Unified_Type_Management.md` |
|
||
| **AI 开发规则** | `docs/05_AI/02_Rules.md` |
|
||
| **项目硬性约束** | `.trae/rules/project-specific-rules.md` |
|
||
|
||
---
|
||
|
||
## 🟠 紧急情况处理
|
||
|
||
### 编译错误
|
||
|
||
```bash
|
||
# 1. 检查类型错误
|
||
npm run typecheck
|
||
|
||
# 2. 修复 ESLint 错误
|
||
npm run lint:fix
|
||
|
||
# 3. 重新编译
|
||
npm run build
|
||
```
|
||
|
||
### 类型错误
|
||
|
||
```typescript
|
||
// 快速修复:使用类型守卫
|
||
if (isUser(data)) {
|
||
// TypeScript 知道 data 是 User 类型
|
||
}
|
||
|
||
// 快速修复:使用 Schema 验证
|
||
const user = UserSchema.parse(data)
|
||
```
|
||
|
||
### 业务逻辑错误
|
||
|
||
```typescript
|
||
// 检查:业务逻辑是否在 Service 层
|
||
// 检查:状态流转是否遵循状态机
|
||
// 检查:权限校验是否完整
|
||
```
|
||
|
||
---
|
||
|
||
*本卡片仅供快速参考,详细规范请查阅完整文档。*
|