静态缓存页面 · 查看动态版本 · 登录
智柴网 登录 | 注册
← 返回话题
✨步子哥 @steper · 2025-11-13 07:04

解读 common-api-service.ts 文件:

文件概述

这是一个使用类(Class)和静态方法(Static Methods)的 API 服务文件,与 agent.ts 的函数式风格不同。它封装了通用的执行器相关 API 调用。

设计模式对比

agent.ts vs common-api-service.ts

特性agent.tscommon-api-service.ts
组织方式导出独立函数类的静态方法
使用方式getAllAgents()CommonApiService.getDetails()
共享状态有(BASE_URL 常量)

类结构分析

1. 基础配置

``21:22:ui-vue3/src/api/common-api-service.ts export class CommonApiService { private static readonly BASE_URL = '/api/executor'

- `private static readonly`:私有静态只读常量
  - `private`:仅在类内部使用
  - `static`:属于类,不依赖实例
  - `readonly`:不可修改
- `BASE_URL`:所有 API 调用的基础路径

### 2. `getDetails` - 获取执行记录详情

25:53:ui-vue3/src/api/common-api-service.ts public static async getDetails(planId: string): Promise { try { const response = await fetch(${this.BASE_URL}/details/${planId}) if (response.status === 404) { // 404 returns null return null } if (!response.ok) { const errorText = await response.text() throw new Error(Failed to get detailed information: ${response.status} - ${errorText}) } const rawText = await response.text() const data = JSON.parse(rawText)

// Type validation - ensure the response contains required currentPlanId if (data && typeof data === 'object' && !data.currentPlanId) { // If currentPlanId is missing from response, add it from the parameter data.currentPlanId = planId }

return data } catch (error: unknown) { // Log error but don't throw exception console.error('[CommonApiService] Failed to get plan details:', error) // Don't return failed status for network errors - let polling continue // Only return null to indicate no data available return null } }

特点:
- 404 返回 `null`(不抛错)
- 数据校验:缺失 `currentPlanId` 时自动补充
- 错误处理:捕获异常并返回 `null`,便于轮询继续
- 使用场景:适合轮询场景,避免因临时错误中断

### 3. `submitFormInput` - 提交表单输入

56:79:ui-vue3/src/api/common-api-service.ts public static async submitFormInput( planId: string, formData: Record ): Promise> { const response = await fetch(
${this.BASE_URL}/submit-input/${planId}, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData), }) if (!response.ok) { let errorData try { errorData = await response.json() } catch { errorData = { message: Failed to submit form input: ${response.status} } } throw new Error(errorData.message || Failed to submit form input: ${response.status}) } const contentType = response.headers.get('content-type') if (contentType && contentType.indexOf('application/json') !== -1) { return await response.json() } return { success: true } }
特点:
- POST 请求,发送 JSON 数据
- 错误处理:解析错误信息并抛出异常
- 响应处理:检查 Content-Type,非 JSON 时返回 `{ success: true }`
- 使用场景:用户交互提交,需要明确的成功/失败反馈

### 4. `getAllPrompts` - 获取所有提示列表

84:93:ui-vue3/src/api/common-api-service.ts static async getAllPrompts(): Promise { try { const response = await fetch(this.BASE_URL) const result = await this.handleResponse(response) return await result.json() } catch (error) { console.error('Failed to get Prompt list:', error) throw error } }
特点:
- 使用私有方法 `handleResponse` 统一处理响应
- 错误会向上抛出,调用方需要处理
- 返回类型为 `unknown[]`(较宽松)

### 5. `handleResponse` - 私有响应处理

95:105:ui-vue3/src/api/common-api-service.ts private static async handleResponse(response: Response) { if (!response.ok) { try { const errorData = await response.json() throw new Error(errorData.message ||
API request failed: ${response.status}) } catch { throw new Error(API request failed: ${response.status} ${response.statusText}) } } return response }
特点:
- `private static`:仅内部使用
- 统一错误处理逻辑
- 尝试解析 JSON 错误,失败则使用状态文本

## 设计模式总结

### 1. 静态方法模式
typescript // 使用方式:不需要实例化 CommonApiService.getDetails('plan-123') // 而不是: const service = new CommonApiService() service.getDetails('plan-123')
### 2. 不同的错误处理策略

| 方法 | 错误处理策略 | 原因 |
|------|------------|------|
| `getDetails` | 捕获异常,返回 `null` | 轮询场景,不应中断 |
| `submitFormInput` | 抛出异常 | 用户操作,需要明确反馈 |
| `getAllPrompts` | 抛出异常 | 调用方处理错误 |

### 3. 数据校验和修复
`getDetails` 中自动补充缺失的 `currentPlanId`,增强健壮性。

## 使用示例

typescript // 获取详情(轮询场景) const details = await CommonApiService.getDetails('plan-123') if (details) { console.log('获取成功:', details) } else { console.log('数据不存在或网络错误') }

// 提交表单(需要错误处理) try { const result = await CommonApiService.submitFormInput('plan-123', { name: 'John', age: 30 }) console.log('提交成功:', result) } catch (error) { console.error('提交失败:', error) } `

agent.ts 的对比

  • agent.ts:函数式,简单直接,适合独立 API
  • common-api-service.ts`:类式,可共享配置和私有方法,适合相关 API 的集中管理
两种方式都有效,选择取决于项目风格和需求。

暂无表态