71 lines
2.7 KiB
Plaintext
71 lines
2.7 KiB
Plaintext
---
|
||
description: next-project API 稳定性与提现规范(仅 next-project 参考,soul-api 为 Go 不适用)
|
||
globs: ["next-project/**/*"]
|
||
alwaysApply: false
|
||
---
|
||
|
||
# API 稳定性与提现模块开发规范(next-project)
|
||
|
||
**适用范围**:本规则仅适用于 **next-project**(Next.js + lib/db.ts)。当前线上后端为 **soul-api**(Go + GORM),不涉及 `query()`、`toArray`、`ensureTableExists`,请勿在 soul-api 中套用本规则。
|
||
|
||
## 核心原则
|
||
|
||
在 **next-project** 中开发 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: []}`,确认通路正常后再分步加回代码。
|