admin / binv-docs /04-api-integration.md
hanbinsite's picture
chore: HuggingFace deploy 2026-05-19 10:37
dc649b1
|
Raw History Blame Contribute Delete
26.5 kB
# A04 - API 对接规范 ## 通用响应格式 所有 API 响应遵循统一的 JSON 结构(由 API 服务定义,前端适配解析): ```typescript // 标准成功响应 interface ApiResponse<T = any> { code: 0; msg: 'success'; data: T; } // 分页列表响应 interface PaginatedData<T> { list: T[]; total: number; page: number; page_size: number; } type PaginatedResponse<T> = ApiResponse<PaginatedData<T>>; // 错误响应 interface ApiError { code: number; // 错误码:40001-40099 鉴权 | 40100-40199 参数 | 40200-40299 业务 | 50000-50099 服务端 msg: string; // 错误描述 data: null; } ``` ### 错误码处理策略 ```typescript // 响应拦截器中的错误码映射 const ERROR_HANDLERS: Record<string, (msg: string) => void> = { // 鉴权错误:清除登录态,跳转登录页 40001: () => { /* token 过期 */ }, 40002: () => { /* 用户名或密码错误 */ }, 40003: () => { /* 权限不足 */ }, // 参数校验错误:表单级提示 40100: (msg) => { /* 弹出 message.warning(msg) */ }, // 业务逻辑错误:操作级提示 40200: (msg) => { /* 弹出 message.error(msg) */ }, // 服务端错误:统一提示 50000: () => { /* 弹出 '服务器错误,请稍后重试' */ }, }; ``` ## TypeScript 类型定义 ### 通用类型 ```typescript // types/api.ts /** 分页查询参数 */ interface PaginationParams { page?: number; // 默认 1 page_size?: number; // 默认 20,最大 100 } /** 排序参数 */ interface SortParams { sort?: string; // 排序字段 order?: 'asc' | 'desc'; // 默认 'desc' } /** 通用查询参数 */ type QueryParams = PaginationParams & SortParams; ``` ### 认证相关 ```typescript // types/auth.ts /** 登录请求 */ interface LoginRequest { username: string; password: string; } /** 登录响应 */ interface LoginResponse { accessToken: string; // JWT token,Vben Admin 约定字段名 expires_in: number; // 有效期(秒) } /** 用户信息(Vben Admin getUserInfo 接口要求) */ interface AdminUserInfo { id: number; username: string; realName: string; // Vben Admin 约定字段,映射后端的 nickname roles: string[]; // Vben Admin 约定字段,如 ["super_admin"] avatar: string | null; } /** 权限码列表 */ type PermissionCodes = string[]; /** 菜单路由节点 */ interface MenuNode { name: string; path: string; component: string | null; redirect: string | null; meta: { title: string; icon: string | null; order: number; hideInMenu: boolean; keepAlive: boolean; }; children: MenuNode[] | null; } /** 权限树节点(角色分配权限用) */ interface PermissionNode { id: number; code: string; name: string; type: 'menu' | 'page' | 'btn'; children: PermissionNode[] | null; } ``` ### 资源站管理 ```typescript // types/source.ts interface SourceItem { id: number; name: string; code: string; base_url: string; site_url: string | null; play_from_m3u8: string | null; play_from_yun: string | null; parse_url: string | null; is_active: boolean; sync_interval: number; last_sync_at: string | null; // ISO8601 last_sync_status: 'success' | 'failed' | 'running' | null; last_sync_count: number; total_count: number; sort_order: number; remark: string | null; created_at: string; } interface SourceCreateRequest { name: string; code: string; base_url: string; site_url?: string; play_from_m3u8?: string; play_from_yun?: string; parse_url?: string; sync_interval?: number; // 默认 60 sort_order?: number; // 默认 0 remark?: string; } type SourceUpdateRequest = Partial<SourceCreateRequest>; interface SourceQueryParams extends PaginationParams { is_active?: boolean; } interface SourceTestResult { is_success: boolean; response_time_ms: number | null; total_count: number | null; error_message: string | null; } interface SourceSyncResponse { task_id: string; status: 'running'; } ``` ### 影片管理 ```typescript // types/vod.ts interface VodSourceBrief { source_id: number; source_name: string; play_from: string; } interface VodAdminItem { id: number; name: string; sub_name: string | null; category_id: number; category_name: string; cover: string | null; actor: string | null; director: string | null; area: string | null; lang: string | null; year: string | null; score: number | null; remarks: string | null; is_end: boolean; is_hidden: boolean; is_recommended: boolean; view_count: number; source_count: number; sources: VodSourceBrief[]; created_at: string; updated_at: string; } interface VodQueryParams extends QueryParams { keyword?: string; category_id?: number; source_id?: number; is_hidden?: boolean; is_recommended?: boolean; is_end?: boolean; year?: string; area?: string; } interface VodUpdateRequest { category_id?: number; is_hidden?: boolean; is_recommended?: boolean; cover?: string; score?: number; } ``` ### 分类管理 ```typescript // types/category.ts interface CategoryMappingItem { source_id: number; source_name: string; source_type_id: number; source_type_name: string; } interface CategoryNode { id: number; name: string; parent_id: number | null; sort_order: number; is_active: boolean; children: CategoryNode[] | null; mappings?: CategoryMappingItem[]; } interface CategoryUpdateRequest { name?: string; sort_order?: number; is_active?: boolean; } interface CategoryMappingRequest { mappings: Array<{ category_id: number; source_id: number; source_type_id: number; source_type_name: string; }>; } ``` ### 用户管理 ```typescript // types/user.ts interface UserMgmtItem { id: number; username: string | null; email: string | null; phone: string | null; nickname: string | null; is_active: boolean; favorite_count: number; history_count: number; last_login_at: string | null; created_at: string; } interface UserQueryParams extends PaginationParams { keyword?: string; is_active?: boolean; } ``` ### 管理员管理 ```typescript // types/admin.ts interface RoleBrief { id: number; name: string; code: string; } interface AdminMgmtItem { id: number; username: string; nickname: string | null; avatar: string | null; is_active: boolean; roles: RoleBrief[]; last_login_at: string | null; created_at: string; } interface AdminCreateRequest { username: string; password: string; nickname?: string; role_ids: number[]; } interface AdminUpdateRequest { nickname?: string; is_active?: boolean; } interface ResetPasswordRequest { new_password: string; } interface AssignRolesRequest { role_ids: number[]; } ``` ### 角色管理 ```typescript // types/role.ts interface PermissionItem { id: number; code: string; name: string; type: 'menu' | 'page' | 'btn'; } interface RoleDetailItem { id: number; name: string; code: string; description: string | null; is_builtin: boolean; status: number; // 1=启用 0=禁用 permissions: PermissionItem[]; admin_count: number; created_at: string; } interface RoleCreateRequest { name: string; code: string; description?: string; permission_ids: number[]; } interface RoleUpdateRequest { name?: string; description?: string; status?: number; } interface AssignPermissionsRequest { permission_ids: number[]; } ``` ### 同步管理 ```typescript // types/sync.ts interface SyncLogItem { id: number; source_id: number; source_name: string; status: 'running' | 'success' | 'failed'; started_at: string; finished_at: string | null; total_fetched: number; new_count: number; update_count: number; fail_count: number; error_message: string | null; duration_seconds: number | null; } interface SyncLogQueryParams extends PaginationParams { source_id?: number; status?: 'success' | 'failed' | 'running'; } interface TriggerSyncRequest { source_id?: number; // null = 同步所有启用站点 full?: boolean; // 默认 false } interface TriggerSyncResponse { task_ids: string[]; } ``` ### 系统配置 ```typescript // types/system.ts interface SystemConfig { site_name: string; site_description: string | null; sync_cron: string; max_sync_concurrent: number; cache_ttl: number; user_register_enabled: boolean; } type SystemConfigUpdateRequest = Partial<SystemConfig>; ``` ## API 接口清单 以下是 Admin 前端需要调用的全部 API 接口,与 API 文档 D04 保持一致: ### 认证模块 | 方法 | 路径 | 说明 | 权限 | | ---- | ------------------------- | -------------- | ------ | | POST | `/admin/auth/login` | 登录 | 无 | | POST | `/admin/auth/logout` | 注销 | 需登录 | | GET | `/admin/auth/user-info` | 获取用户信息 | 需登录 | | GET | `/admin/auth/codes` | 获取权限码列表 | 需登录 | | GET | `/admin/auth/menus` | 获取菜单路由树 | 需登录 | | GET | `/admin/auth/permissions` | 获取完整权限树 | 需登录 | ### 资源站管理 | 方法 | 路径 | 说明 | 权限码 | | ------ | --------------------------- | ---------- | ------------------- | | GET | `/admin/source` | 列表 | `source:list` | | POST | `/admin/source` | 新增 | `source:create` | | GET | `/admin/source/{id}` | 详情 | `source:detail` | | PUT | `/admin/source/{id}` | 更新 | `source:update` | | DELETE | `/admin/source/{id}` | 删除 | `source:btn:delete` | | POST | `/admin/source/{id}/test` | 测试连通性 | `source:btn:test` | | POST | `/admin/source/{id}/sync` | 手动同步 | `source:btn:sync` | | PUT | `/admin/source/{id}/enable` | 启用/禁用 | `source:btn:enable` | ### 影片管理 | 方法 | 路径 | 说明 | 权限码 | | ------ | --------------------------- | --------- | ------------------- | | GET | `/admin/vod` | 列表 | `vod:list` | | GET | `/admin/vod/{id}` | 详情 | `vod:detail` | | PUT | `/admin/vod/{id}` | 更新 | `vod:update` | | DELETE | `/admin/vod/{id}` | 删除 | `vod:btn:delete` | | PUT | `/admin/vod/{id}/hide` | 隐藏/显示 | `vod:btn:hide` | | PUT | `/admin/vod/{id}/recommend` | 推荐/取消 | `vod:btn:recommend` | ### 分类管理 | 方法 | 路径 | 说明 | 权限码 | | ---- | ------------------------- | ------------ | ------------------ | | GET | `/admin/category` | 列表(树形) | `category:list` | | PUT | `/admin/category/{id}` | 更新 | `category:update` | | PUT | `/admin/category/mapping` | 批量更新映射 | `category:btn:map` | ### 用户管理 | 方法 | 路径 | 说明 | 权限码 | | ------ | ---------------------- | --------- | ----------------- | | GET | `/admin/user` | 列表 | `user:list` | | GET | `/admin/user/{id}` | 详情 | `user:detail` | | PUT | `/admin/user/{id}/ban` | 封禁/解封 | `user:btn:ban` | | DELETE | `/admin/user/{id}` | 删除 | `user:btn:delete` | ### 管理员管理 | 方法 | 路径 | 说明 | 权限码 | | --- | --- | --- | --- | | GET | `/admin/admin` | 列表 | `admin:list` | | POST | `/admin/admin` | 新增 | `admin:create` | | PUT | `/admin/admin/{id}` | 更新 | `admin:update` | | DELETE | `/admin/admin/{id}` | 删除 | `admin:delete` | | PUT | `/admin/admin/{id}/reset-password` | 重置密码 | `admin:btn:reset_pwd` | | PUT | `/admin/admin/{id}/assign-roles` | 分配角色 | `admin:btn:assign_role` | ### 角色管理 | 方法 | 路径 | 说明 | 权限码 | | ------ | ------------------------------ | -------- | ---------------------- | | GET | `/admin/role` | 列表 | `role:list` | | POST | `/admin/role` | 新增 | `role:create` | | PUT | `/admin/role/{id}` | 更新 | `role:update` | | DELETE | `/admin/role/{id}` | 删除 | `role:delete` | | PUT | `/admin/role/{id}/permissions` | 分配权限 | `role:btn:assign_perm` | ### 同步管理 | 方法 | 路径 | 说明 | 权限码 | | ---- | --------------------- | ------------ | ------------------ | | GET | `/admin/sync/log` | 日志列表 | `sync:list` | | POST | `/admin/sync/trigger` | 触发全量同步 | `sync:btn:trigger` | ### 系统配置 | 方法 | 路径 | 说明 | 权限码 | | ---- | ---------------------- | -------- | ----------------- | | GET | `/admin/system/config` | 获取配置 | `system:config` | | PUT | `/admin/system/config` | 更新配置 | `system:btn:save` | ## Mock 配置 在开发阶段,可使用 Vben Admin 内置的 Mock 系统或 vite-plugin-mock 进行接口模拟,无需依赖后端 API 服务即可进行前端开发。 ### 目录结构 ``` apps/web-ele/ ├── mock/ │ ├── auth.mock.ts # 认证接口 mock │ ├── source.mock.ts # 资源站管理 mock │ ├── vod.mock.ts # 影片管理 mock │ ├── category.mock.ts # 分类管理 mock │ ├── user.mock.ts # 用户管理 mock │ ├── admin.mock.ts # 管理员管理 mock │ ├── role.mock.ts # 角色管理 mock │ ├── sync.mock.ts # 同步管理 mock │ └── system.mock.ts # 系统配置 mock ``` ### Mock 示例 ```typescript // mock/auth.mock.ts import type { MockMethod } from 'vite-plugin-mock'; export default [ // 登录 { url: '/api/admin/auth/login', method: 'post', response: ({ body }: { body: { username: string; password: string } }) => { if (body.username === 'admin' && body.password === 'admin123') { return { code: 0, msg: 'success', data: { accessToken: 'mock_jwt_token_super_admin', expires_in: 7200, }, }; } return { code: 40001, msg: '用户名或密码错误', data: null, }; }, }, // 获取用户信息 { url: '/api/admin/auth/user-info', method: 'get', response: () => ({ code: 0, msg: 'success', data: { id: 1, username: 'admin', realName: '超级管理员', roles: ['super_admin'], avatar: null, }, }), }, // 获取权限码 { url: '/api/admin/auth/codes', method: 'get', response: () => ({ code: 0, msg: 'success', data: [ 'source:menu', 'source:list', 'source:detail', 'source:create', 'source:update', 'source:btn:sync', 'source:btn:enable', 'source:btn:delete', 'source:btn:test', 'vod:menu', 'vod:list', 'vod:detail', 'vod:create', 'vod:update', 'vod:btn:hide', 'vod:btn:recommend', 'vod:btn:delete', 'vod:btn:audit', 'category:menu', 'category:list', 'category:update', 'category:btn:map', 'user:menu', 'user:list', 'user:detail', 'user:btn:ban', 'user:btn:delete', 'admin:menu', 'admin:list', 'admin:create', 'admin:update', 'admin:delete', 'admin:btn:assign_role', 'admin:btn:reset_pwd', 'role:menu', 'role:list', 'role:create', 'role:update', 'role:delete', 'role:btn:assign_perm', 'sync:menu', 'sync:list', 'sync:btn:trigger', 'sync:btn:cancel', 'system:menu', 'system:config', 'system:btn:save', ], }), }, // 获取菜单 { url: '/api/admin/auth/menus', method: 'get', response: () => ({ code: 0, msg: 'success', data: [ { name: 'Dashboard', path: '/dashboard', component: '/dashboard/index', redirect: null, meta: { title: '仪表盘', icon: 'lucide:layout-dashboard', order: 0, hideInMenu: false, keepAlive: false, }, children: null, }, { name: 'SourceManage', path: '/source', component: '/source/index', redirect: null, meta: { title: '资源站管理', icon: 'lucide:database', order: 1, hideInMenu: false, keepAlive: false, }, children: null, }, { name: 'VodManage', path: '/vod', component: '/vod/index', redirect: null, meta: { title: '影片管理', icon: 'lucide:film', order: 2, hideInMenu: false, keepAlive: false, }, children: null, }, { name: 'CategoryManage', path: '/category', component: '/category/index', redirect: null, meta: { title: '分类管理', icon: 'lucide:folder-tree', order: 3, hideInMenu: false, keepAlive: false, }, children: null, }, { name: 'SyncManage', path: '/sync', component: '/sync/index', redirect: null, meta: { title: '同步管理', icon: 'lucide:refresh-cw', order: 4, hideInMenu: false, keepAlive: false, }, children: null, }, { name: 'SystemManage', path: '/system', component: null, redirect: '/user', meta: { title: '系统管理', icon: 'lucide:settings', order: 5, hideInMenu: false, keepAlive: false, }, children: [ { name: 'UserManage', path: '/user', component: '/user/index', redirect: null, meta: { title: '用户管理', icon: 'lucide:users', order: 0, hideInMenu: false, keepAlive: false, }, children: null, }, { name: 'AdminManage', path: '/admin', component: '/admin/index', redirect: null, meta: { title: '管理员管理', icon: 'lucide:user-cog', order: 1, hideInMenu: false, keepAlive: false, }, children: null, }, { name: 'RoleManage', path: '/role', component: '/role/index', redirect: null, meta: { title: '角色管理', icon: 'lucide:shield', order: 2, hideInMenu: false, keepAlive: false, }, children: null, }, { name: 'ConfigManage', path: '/system/config', component: '/system/index', redirect: null, meta: { title: '系统配置', icon: 'lucide:sliders', order: 3, hideInMenu: false, keepAlive: false, }, children: null, }, ], }, ], }), }, ] as MockMethod[]; ``` ```typescript // mock/source.mock.ts import type { MockMethod } from 'vite-plugin-mock'; const mockSources = [ { id: 1, name: '金鹰资源', code: 'jinying', base_url: 'https://jyzyapi.com/provide/vod/', site_url: null, play_from_m3u8: 'jinyingm3u8', play_from_yun: 'jinyingyun', parse_url: 'https://hd.iapijy.com/play?url=', is_active: true, sync_interval: 60, last_sync_at: '2025-01-15T10:30:00', last_sync_status: 'success', last_sync_count: 156, total_count: 12680, sort_order: 1, remark: null, created_at: '2025-01-01T00:00:00', }, { id: 2, name: '量子资源', code: 'liangzi', base_url: 'https://cj.lziapi.com/api.php/provide/vod/', site_url: null, play_from_m3u8: 'liangzim3u8', play_from_yun: 'liangziyun', parse_url: null, is_active: true, sync_interval: 120, last_sync_at: '2025-01-15T09:00:00', last_sync_status: 'success', last_sync_count: 89, total_count: 9530, sort_order: 0, remark: null, created_at: '2025-01-05T00:00:00', }, ]; export default [ { url: '/api/admin/source', method: 'get', response: ({ query }: { query: Record<string, any> }) => { let list = [...mockSources]; if (query.is_active !== undefined) { list = list.filter((s) => s.is_active === (query.is_active === 'true')); } const page = Number(query.page) || 1; const pageSize = Number(query.page_size) || 20; return { code: 0, msg: 'success', data: { list: list.slice((page - 1) * pageSize, page * pageSize), total: list.length, page, page_size: pageSize, }, }; }, }, { url: '/api/admin/source', method: 'post', response: ({ body }: { body: any }) => ({ code: 0, msg: 'success', data: { id: Date.now(), ...body, created_at: new Date().toISOString() }, }), }, { url: '/api/admin/source/:id/test', method: 'post', response: () => ({ code: 0, msg: 'success', data: { is_success: true, response_time_ms: 234, total_count: 12680, error_message: null, }, }), }, { url: '/api/admin/source/:id/sync', method: 'post', response: ({ params }: { params: Record<string, string> }) => ({ code: 0, msg: 'success', data: { task_id: `task_${params.id}_${Date.now()}`, status: 'running' }, }), }, ] as MockMethod[]; ``` ### Mock 开关 ```typescript // vite.config.ts import { viteMockServe } from 'vite-plugin-mock'; export default defineConfig(({ command }) => ({ plugins: [ viteMockServe({ mockPath: 'mock', enable: command === 'serve', // 仅开发环境启用 mock logger: true, // 控制台打印请求日志 }), ], })); ``` ## Vite 代理配置 ```typescript // vite.config.ts export default defineConfig({ server: { port: 5173, proxy: { '/api': { target: 'http://localhost:8000', // API 服务开发地址 changeOrigin: true, // rewrite 无需,因为 API 路径直接匹配 /api/* }, }, }, }); ``` ### 代理说明 | 场景 | 前端请求 | 代理转发 | 说明 | | --- | --- | --- | --- | | 开发环境 + Mock | `GET /api/admin/source` | Mock 拦截 | Mock 插件优先级高于代理 | | 开发环境 + 真实 API | `GET /api/admin/source` | `http://localhost:8000/api/admin/source` | 关闭 Mock 后走代理 | | 生产环境 | `GET /api/admin/source` | Nginx 反向代理 | 无 Vite 代理,由 Nginx 处理 | ## 请求层完整封装示例 ```typescript // api/request.ts import axios, { type AxiosResponse, type InternalAxiosRequestConfig, } from 'axios'; import { ElMessage } from 'element-plus'; import { useAuthStore } from '#/store/auth'; const service = axios.create({ baseURL: import.meta.env.VITE_API_BASE_URL || '/api', timeout: 30000, }); // 请求拦截器 service.interceptors.request.use( (config: InternalAxiosRequestConfig) => { const authStore = useAuthStore(); if (authStore.accessToken) { config.headers.Authorization = `Bearer ${authStore.accessToken}`; } return config; }, (error) => Promise.reject(error), ); // 响应拦截器 service.interceptors.response.use( (response: AxiosResponse<{ code: number; msg: string; data: any }>) => { const { code, msg, data } = response.data; if (code === 0) { return data; // 直接返回 data,业务层无需判断 code } // 鉴权错误 if (code >= 40001 && code < 40099) { ElMessage.error(msg || '登录已过期,请重新登录'); const authStore = useAuthStore(); authStore.logout(); return Promise.reject(new Error(msg)); } // 参数/业务错误 ElMessage.error(msg || '操作失败'); return Promise.reject(new Error(msg)); }, (error) => { if (error.code === 'ECONNABORTED') { ElMessage.error('请求超时,请稍后重试'); } else if (!error.response) { ElMessage.error('网络错误,请检查网络连接'); } else { ElMessage.error(`服务器错误: ${error.response.status}`); } return Promise.reject(error); }, ); export default service; ``` ```typescript // api/index.ts export { default as requestClient } from './request'; // 按模块导出 API 函数 export * from './core/auth'; export * from './core/source'; export * from './core/vod'; export * from './core/category'; export * from './core/user'; export * from './core/admin'; export * from './core/role'; export * from './core/sync'; export * from './core/system'; ``` ## API 文档版本对应关系 | 文档 | API 项目 | Admin 项目 | | -------- | ------------------ | -------------------- | | 概述 | D01 - API 项目概述 | A01 - Admin 项目概述 | | 功能设计 | D02 - API 功能设计 | A02 - Admin 功能设计 | | 架构 | D03 - API 架构设计 | A03 - Admin 架构设计 | | API 设计 | D04 - API 接口设计 | A04 - API 对接规范 | 两个项目共享相同的权限码体系、API 端点路径和数据结构定义,本文档中的 TypeScript 类型直接对应 D04 中定义的 Pydantic Schema。
# A04 - API 对接规范
## 通用响应格式
所有 API 响应遵循统一的 JSON 结构(由 API 服务定义,前端适配解析):
```typescript
// 标准成功响应
interface ApiResponse<T = any> {
code: 0;
msg: 'success';
data: T;
}
// 分页列表响应
interface PaginatedData<T> {
list: T[];
total: number;
page: number;
page_size: number;
}
type PaginatedResponse<T> = ApiResponse<PaginatedData<T>>;
// 错误响应
interface ApiError {
code: number; // 错误码:40001-40099 鉴权 | 40100-40199 参数 | 40200-40299 业务 | 50000-50099 服务端
msg: string; // 错误描述
data: null;
}
```
### 错误码处理策略
```typescript
// 响应拦截器中的错误码映射
const ERROR_HANDLERS: Record<string, (msg: string) => void> = {
// 鉴权错误:清除登录态,跳转登录页
40001: () => {
/* token 过期 */
},
40002: () => {
/* 用户名或密码错误 */
},
40003: () => {
/* 权限不足 */
},
// 参数校验错误:表单级提示
40100: (msg) => {
/* 弹出 message.warning(msg) */
},
// 业务逻辑错误:操作级提示
40200: (msg) => {
/* 弹出 message.error(msg) */
},
// 服务端错误:统一提示
50000: () => {
/* 弹出 '服务器错误,请稍后重试' */
},
};
```
## TypeScript 类型定义
### 通用类型
```typescript
// types/api.ts
/** 分页查询参数 */
interface PaginationParams {
page?: number; // 默认 1
page_size?: number; // 默认 20,最大 100
}
/** 排序参数 */
interface SortParams {
sort?: string; // 排序字段
order?: 'asc' | 'desc'; // 默认 'desc'
}
/** 通用查询参数 */
type QueryParams = PaginationParams & SortParams;
```
### 认证相关
```typescript
// types/auth.ts
/** 登录请求 */
interface LoginRequest {
username: string;
password: string;
}
/** 登录响应 */