Files
easygoadmin-wiki/EasyGoAdmin_GoFrame_EleVue/zh/frontend/api-module.md
T
2026-10-20 21:19:44 +08:00

121 lines
3.4 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.
# 9.13 API 模块编写规范
:::tip 概述
api 模块按域组织(src/api/{域}/{模块}.ts),每接口一个导出函数,内部 http.request 调用。url 对齐后端 gmeta path(无 /api 前缀、无 /v1)。本节给出规范与真实示例。
:::
## 文件组织
```text
src/api/{域}/{模块}.ts 域与后端模块域一致(system/data/content/monitor/tool)
src/api/common/*.ts 跨域公共接口(city/index/menu/user)
命名:驼峰(fileTemplate.ts、onlineUser.ts、cacheMonitor.ts)
函数命名:get{Mod}Page / get{Mod}Detail / {mod}Add / {mod}Update /
{mod}Delete / {mod}BatchDelete / {mod}Import / {mod}Export
```
## 真实示例(摘自 src/api/tool/example.ts)
```ts
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,
});
}
/**
* 根据 ID 获取案例演示详情
*
* @param id 案例演示ID
* @returns 案例演示详情数据
*/
export function getExampleDetail(id) {
return http.request({
url: '/example/detail/' + id,
method: 'get',
});
}
/**
* 添加案例演示
*
* @param data 案例演示数据
* @returns 新记录的 ID
*/
export function exampleAdd(data: any) {
return http.request({
url: '/example/add',
method: 'POST',
data,
});
}
```
## url 对齐规则
```text
前端 api url 后端 gmeta path 说明
'/example/page' ↔ /api/example/page baseURL 已含 /api
'/example/detail/' + id ↔ /api/example/detail/:id 路由参数拼接
'/config/item/page' ↔ /api/config/item/page 子资源前缀对齐
禁止:写 '/api/example/page'(重复);写 '/v1/...'(无版本段)
```
## 请求方法与参数位置
| 方法 | 参数位置 | 说明 |
|------|---------|------|
| GET | params | 查询参数(分页/筛选/路由参数) |
| POST/PUT | data | JSON body(AddReq/UpdateReq 结构) |
| DELETE | url 路径参数 或 data | /delete/:id 走路径;/batchDelete 走 data {ids:[]} |
## 导入导出函数
```ts
// 导入:multipart(组件内组装 FormData,api 层可直接透传)
export function exampleImport(data: any) {
return http.request({
url: '/example/import',
method: 'POST',
data, // FormData(Content-Type 自动 multipart)
});
}
// 导出:GET + 筛选参数(导出=所见)
export function getExampleExport(params?: Record<string, any>) {
return http.request({
url: '/example/export',
method: 'GET',
params,
});
}
```
## 编写规约
```text
1. 一接口一函数,JSDoc 注释(参数/返回/用途)——生成器模板同款风格
2. url 从后端 gmeta path 抄写(去掉 /api 前缀),改动后端 path 同步前端
3. method 与 gmeta method 一致(大小写不敏感但团队统一大写 GET/POST/PUT/DELETE)
4. 不在 api 层做数据加工(transform 解包已完成;加工放页面/组合式函数)
5. 复杂请求(上传/下载/超时定制)用 RequestOptions 第三参数定制
6. 新增函数后对照 /api.json 核对路径与方法
```