Files
soul-yongping/.cursor/rules/api-reliability.md

51 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# API 稳定性与提现模块开发规范
## 核心原则
在本项目中开发 API尤其是涉及财务和管理后台的接口必须遵守以下稳定性规则以防止常见的 JavaScript 运行时错误。
## 1. 数据库查询安全性 (防御 `undefined.length`)
**问题背景**`lib/db.ts` 中的 `query()` 在网络波动或表不存在时可能返回 `undefined`
**要求**
- 所有调用 `query()` 的结果必须经过 `toArray` 处理。
- 在 API 文件顶部定义 `toArray` 辅助函数:
```typescript
function toArray<T>(x: any): T[] {
if (x == null) return [];
if (Array.isArray(x)) return x;
return [x];
}
```
- 使用方式:`const rows = toArray(await query(sql))`
## 2. 数据库自愈 (Self-Healing Tables)
**要求**
-`GET` 接口逻辑开始前,必须调用 `ensureTableExists()` 函数。
- 确保核心表(如 `withdrawals`)在查询前已存在,避免 `Table 'xxx' doesn't exist` 导致的 500 错误。
## 3. 提现模块状态映射
**映射标准**
- **数据库存值**`pending` (待处理), `processing` (处理中), `success` (成功), `failed` (失败)
- **前端显示值**`pending`, `processing`, `completed` (已完成), `rejected` (已拒绝)
- **转换逻辑**
```typescript
const displayStatus = dbStatus === 'success' ? 'completed' : (dbStatus === 'failed' ? 'rejected' : dbStatus);
```
## 4. 财务字段处理
- **金额转换**:从数据库读取的 `decimal` 类型必须经过 `parseFloat()` 转换后再进行数学运算。
- **配置归一化**:分成比例字段(如 `distributorShare`)必须兼容 `90``0.9` 两种存值:
```typescript
let rate = Number(val);
if (rate >= 1) rate = rate / 100; // 将 90 转为 0.9
```
## 5. 管理后台列表必备字段
所有管理后台的 API 必须包含以下映射字段以支持通用 UI 组件:
- `user_name``userNickname`: 展示用户名称。
- `userAvatar`: 展示头像(若无,前端需展示首字母)。
- `status`: 统一后的显示状态。
- `amount`: 格式化后的数字金额。
## 6. 调试模式
- 遇到顽固 500 错误时,优先采用“最小化接口法”:移除所有业务逻辑,仅返回 `{success: true, data: []}`,确认通路正常后再分步加回代码。