112 lines
2.9 KiB
Markdown
112 lines
2.9 KiB
Markdown
# 9.14 API 模块编写规范
|
||
|
||
:::tip 概述
|
||
api 模块是前端与后端契约的镜像:按业务域分组、一模块一文件、函数对应后端动作。命名与写法以 `ui/src/api/tool/example.ts` 为参考实现。
|
||
:::
|
||
|
||
## 文件组织
|
||
|
||
```text
|
||
ui/src/api/{域}/{模块}.ts
|
||
```
|
||
|
||
域与 views 一一对应(system/content/data/monitor/tool/file/setting...)。公共聚合接口放 common/。
|
||
|
||
## 命名约定(以 example 为参照)
|
||
|
||
| 动作 | 命名模式 | example 实际函数 |
|
||
|---|---|---|
|
||
| 分页 | get{模块}Page | getExamplePage |
|
||
| 列表 | get{模块}List | getExampleList |
|
||
| 详情 | get{模块}Detail | getExampleDetail |
|
||
| 新增 | {模块}Add | exampleAdd |
|
||
| 修改 | {模块}Update | exampleUpdate |
|
||
| 删除 | {模块}Delete | exampleDelete |
|
||
| 批量删除 | {模块}BatchDelete | exampleBatchDelete |
|
||
| 导入/导出 | {模块}Import / {模块}Export | exampleImport / exampleExport |
|
||
|
||
查询类以 `get` 开头,命令类直接以模块名开头。
|
||
|
||
## 标准写法(摘自 ui/src/api/tool/example.ts)
|
||
|
||
```typescript
|
||
import { http } from '@/utils/http/axios';
|
||
|
||
/**
|
||
* 获取案例演示分页列表
|
||
*
|
||
* @param params 查询参数,包含 pageNo、pageSize 及业务筛选条件
|
||
* @returns 分页结果,含 records、total、size、current、pages
|
||
*/
|
||
export function getExamplePage(params?: Record<string, any>) {
|
||
return http.request({
|
||
url: '/example/page',
|
||
method: 'GET',
|
||
params,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 添加案例演示
|
||
*
|
||
* @param data 案例演示数据
|
||
* @returns 新记录的 ID
|
||
*/
|
||
export function exampleAdd(data: any) {
|
||
return http.request({
|
||
url: '/example/add',
|
||
method: 'POST',
|
||
data,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 删除案例演示
|
||
*
|
||
* @param id 案例演示ID
|
||
* @returns 操作结果
|
||
*/
|
||
export function exampleDelete(id) {
|
||
return http.request({
|
||
url: '/example/delete/' + id,
|
||
method: 'DELETE',
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 批量删除案例演示
|
||
*
|
||
* @param data 含 ids 数组的对象,形如 { ids: [1, 2, 3] }
|
||
* @returns 操作结果
|
||
*/
|
||
export function exampleBatchDelete(data: any) {
|
||
return http.request({
|
||
url: '/example/batchDelete',
|
||
method: 'DELETE',
|
||
data,
|
||
});
|
||
}
|
||
```
|
||
|
||
## 规范要点
|
||
|
||
| 要点 | 说明 |
|
||
|---|---|
|
||
| import 来源 | `import { http } from '@/utils/http/axios'` |
|
||
| URL 不带 /api | 前缀由 VITE_GLOB_API_URL_PREFIX 统一拼接 |
|
||
| 只导出函数 | 每函数带 JSDoc(参数/返回说明);不放状态、不 catch |
|
||
| DELETE 带 body | 批量删除用 `method: 'DELETE', data`(后端 UnmarshalBody 支持) |
|
||
| 文件类接口 | 导入传 FormData;导出返回文件 URL 字符串 |
|
||
| 与 RouteSpec 同步 | 后端加接口 → api 模块加函数,同一 PR |
|
||
|
||
## 禁则
|
||
|
||
- 不在 api 模块拼完整 URL 域名(部署可变)
|
||
- 不在 api 模块做数据变换(变换归页面或工具函数)
|
||
- 不绕过 http 封装直接用 axios 实例
|
||
|
||
## 相关
|
||
|
||
- [9.4 HTTP 请求封装](/zh/frontend/http.html)
|
||
- [6.22 示例模块(example)](/zh/modules/example.html)
|