@openuverse/uvapi 0.0.0-stage → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3871 -3
- package/dist/_virtual/_commonjsHelpers.js +6 -0
- package/dist/_virtual/index.js +4 -0
- package/dist/api/RestAPIClient.d.ts +191 -0
- package/dist/api/RestAPIClient.js +328 -0
- package/dist/api/WebSocketClient.d.ts +174 -0
- package/dist/api/WebSocketClient.js +277 -0
- package/dist/api/index.d.ts +6 -0
- package/dist/api/modules/index.d.ts +2 -0
- package/dist/api/modules/task.d.ts +124 -0
- package/dist/api/modules/task.js +121 -0
- package/dist/api/modules/user.d.ts +114 -0
- package/dist/api/modules/user.js +113 -0
- package/dist/config/index.d.ts +120 -0
- package/dist/config/index.js +112 -0
- package/dist/hooks/index.d.ts +1 -0
- package/dist/hooks/useAttributeMonitor.d.ts +45 -0
- package/dist/hooks/useAttributeMonitor.js +115 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +93 -0
- package/dist/locale/de-DE.d.ts +18 -0
- package/dist/locale/de-DE.js +20 -0
- package/dist/locale/en-US.d.ts +18 -0
- package/dist/locale/en-US.js +20 -0
- package/dist/locale/es-ES.d.ts +18 -0
- package/dist/locale/es-ES.js +20 -0
- package/dist/locale/fr-FR.d.ts +18 -0
- package/dist/locale/fr-FR.js +20 -0
- package/dist/locale/id-ID.d.ts +18 -0
- package/dist/locale/id-ID.js +20 -0
- package/dist/locale/index.d.ts +19 -0
- package/dist/locale/index.js +70 -0
- package/dist/locale/ja-JP.d.ts +18 -0
- package/dist/locale/ja-JP.js +20 -0
- package/dist/locale/ko-KR.d.ts +18 -0
- package/dist/locale/ko-KR.js +20 -0
- package/dist/locale/pl-PL.d.ts +18 -0
- package/dist/locale/pl-PL.js +20 -0
- package/dist/locale/pt-BR.d.ts +18 -0
- package/dist/locale/pt-BR.js +20 -0
- package/dist/locale/ru-RU.d.ts +18 -0
- package/dist/locale/ru-RU.js +20 -0
- package/dist/locale/th-TH.d.ts +18 -0
- package/dist/locale/th-TH.js +20 -0
- package/dist/locale/zh-CN.d.ts +18 -0
- package/dist/locale/zh-CN.js +20 -0
- package/dist/locale/zh-TW.d.ts +18 -0
- package/dist/locale/zh-TW.js +20 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/CachedKeyDecoder.js +38 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/DecodeError.js +14 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/Decoder.js +474 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/Encoder.js +232 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/ExtData.js +8 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/ExtensionCodec.js +46 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/decode.js +7 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/encode.js +7 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/timestamp.js +66 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/utils/int.js +24 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/utils/prettyByte.js +6 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/utils/typedArrays.js +9 -0
- package/dist/node_modules/@msgpack/msgpack/dist.esm/utils/utf8.js +93 -0
- package/dist/node_modules/axios/index.js +38 -0
- package/dist/node_modules/axios/lib/adapters/adapters.js +55 -0
- package/dist/node_modules/axios/lib/adapters/fetch.js +169 -0
- package/dist/node_modules/axios/lib/adapters/xhr.js +72 -0
- package/dist/node_modules/axios/lib/axios.js +46 -0
- package/dist/node_modules/axios/lib/cancel/CancelToken.js +77 -0
- package/dist/node_modules/axios/lib/cancel/CanceledError.js +11 -0
- package/dist/node_modules/axios/lib/cancel/isCancel.js +6 -0
- package/dist/node_modules/axios/lib/core/Axios.js +136 -0
- package/dist/node_modules/axios/lib/core/AxiosError.js +56 -0
- package/dist/node_modules/axios/lib/core/AxiosHeaders.js +181 -0
- package/dist/node_modules/axios/lib/core/InterceptorManager.js +58 -0
- package/dist/node_modules/axios/lib/core/buildFullPath.js +9 -0
- package/dist/node_modules/axios/lib/core/dispatchRequest.js +31 -0
- package/dist/node_modules/axios/lib/core/mergeConfig.js +70 -0
- package/dist/node_modules/axios/lib/core/settle.js +14 -0
- package/dist/node_modules/axios/lib/core/transformData.js +13 -0
- package/dist/node_modules/axios/lib/defaults/index.js +89 -0
- package/dist/node_modules/axios/lib/defaults/transitional.js +8 -0
- package/dist/node_modules/axios/lib/env/data.js +4 -0
- package/dist/node_modules/axios/lib/helpers/AxiosURLSearchParams.js +33 -0
- package/dist/node_modules/axios/lib/helpers/HttpStatusCode.js +71 -0
- package/dist/node_modules/axios/lib/helpers/bind.js +8 -0
- package/dist/node_modules/axios/lib/helpers/buildURL.js +23 -0
- package/dist/node_modules/axios/lib/helpers/combineURLs.js +6 -0
- package/dist/node_modules/axios/lib/helpers/composeSignals.js +30 -0
- package/dist/node_modules/axios/lib/helpers/cookies.js +32 -0
- package/dist/node_modules/axios/lib/helpers/formDataToJSON.js +31 -0
- package/dist/node_modules/axios/lib/helpers/isAbsoluteURL.js +6 -0
- package/dist/node_modules/axios/lib/helpers/isAxiosError.js +7 -0
- package/dist/node_modules/axios/lib/helpers/isURLSameOrigin.js +8 -0
- package/dist/node_modules/axios/lib/helpers/null.js +4 -0
- package/dist/node_modules/axios/lib/helpers/parseHeaders.js +30 -0
- package/dist/node_modules/axios/lib/helpers/parseProtocol.js +7 -0
- package/dist/node_modules/axios/lib/helpers/progressEventReducer.js +35 -0
- package/dist/node_modules/axios/lib/helpers/resolveConfig.js +33 -0
- package/dist/node_modules/axios/lib/helpers/speedometer.js +19 -0
- package/dist/node_modules/axios/lib/helpers/spread.js +8 -0
- package/dist/node_modules/axios/lib/helpers/throttle.js +15 -0
- package/dist/node_modules/axios/lib/helpers/toFormData.js +85 -0
- package/dist/node_modules/axios/lib/helpers/toURLEncodedForm.js +14 -0
- package/dist/node_modules/axios/lib/helpers/trackStream.js +63 -0
- package/dist/node_modules/axios/lib/helpers/validator.js +54 -0
- package/dist/node_modules/axios/lib/platform/browser/classes/Blob.js +4 -0
- package/dist/node_modules/axios/lib/platform/browser/classes/FormData.js +4 -0
- package/dist/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js +5 -0
- package/dist/node_modules/axios/lib/platform/browser/index.js +15 -0
- package/dist/node_modules/axios/lib/platform/common/utils.js +9 -0
- package/dist/node_modules/axios/lib/platform/index.js +9 -0
- package/dist/node_modules/axios/lib/utils.js +237 -0
- package/dist/node_modules/postcss-pxtorem/index.js +109 -0
- package/dist/node_modules/postcss-pxtorem/lib/filter-prop-list.js +13 -0
- package/dist/node_modules/postcss-pxtorem/lib/pixel-unit-regex.js +7 -0
- package/dist/node_modules/postcss-pxtorem/lib/type.js +14 -0
- package/dist/preload/index.d.ts +125 -0
- package/dist/preload/index.js +79 -0
- package/dist/store/index.d.ts +1 -0
- package/dist/store/storeFactory.d.ts +584 -0
- package/dist/store/storeFactory.js +216 -0
- package/dist/theme/index.d.ts +1 -0
- package/dist/theme/index.js +14 -0
- package/dist/types/index.d.ts +57 -0
- package/dist/types/uVerseAPI.d.ts +67 -0
- package/dist/utils/_internal.d.ts +14 -0
- package/dist/utils/_internal.js +72 -0
- package/dist/utils/constance.d.ts +16 -0
- package/dist/utils/constance.js +7 -0
- package/dist/utils/index.d.ts +79 -0
- package/dist/utils/index.js +96 -0
- package/dist/utils/logger.d.ts +118 -0
- package/dist/utils/logger.js +170 -0
- package/dist/utils/px2rem/remAdapter.d.ts +17 -0
- package/dist/utils/px2rem/remAdapter.js +62 -0
- package/dist/utils/px2rem/vite.d.ts +14 -0
- package/dist/utils/px2rem/vite.js +33 -0
- package/package.json +102 -4
package/README.md
CHANGED
|
@@ -1,3 +1,3871 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
[](http://172.16.164.16:9000/dashboard?id=UltraVIEW_uvtools_ui_sdk_6a2a291e-25db-41e3-aeeb-29c88f26b451)
|
|
2
|
+
[](http://172.16.164.16:9000/dashboard?id=UltraVIEW_uvtools_ui_sdk_6a2a291e-25db-41e3-aeeb-29c88f26b451)
|
|
3
|
+
[](http://172.16.164.16:9000/dashboard?id=UltraVIEW_uvtools_ui_sdk_6a2a291e-25db-41e3-aeeb-29c88f26b451)
|
|
4
|
+
[](http://172.16.164.16:9000/dashboard?id=UltraVIEW_uvtools_ui_sdk_6a2a291e-25db-41e3-aeeb-29c88f26b451)
|
|
5
|
+
[](http://172.16.164.16:9000/dashboard?id=UltraVIEW_uvtools_ui_sdk_6a2a291e-25db-41e3-aeeb-29c88f26b451)
|
|
6
|
+
|
|
7
|
+
# Rigol UV API
|
|
8
|
+
|
|
9
|
+
基于 TypeScript 和 Axios 构建的现代化 API 客户端库,提供用户管理、任务管理等完整的业务功能。
|
|
10
|
+
|
|
11
|
+
## 📑 目录
|
|
12
|
+
|
|
13
|
+
- [✨ 特性](#-特性)
|
|
14
|
+
- [📦 安装](#-安装)
|
|
15
|
+
- [🚀 快速开始](#-快速开始)
|
|
16
|
+
- [📚 API 文档](#-api-文档)
|
|
17
|
+
- [UserClient - 用户管理](#userclient---用户管理)
|
|
18
|
+
- [TaskClient - 任务管理](#taskclient---任务管理)
|
|
19
|
+
- [RestAPIClient - REST API 基础客户端](#restapiclient---rest-api-基础客户端)
|
|
20
|
+
- [WebSocketClient - WebSocket 连接管理](#websocketclient---websocket-连接管理)
|
|
21
|
+
- [🗄️ Store 状态管理](#️-store-状态管理)
|
|
22
|
+
- [createStore - 创建 Store (不建议使用)](#createstore---创建-store)
|
|
23
|
+
- [defineStore - 定义并注册 Store (不建议使用)](#definestore---定义并注册-store)
|
|
24
|
+
- [useStore - 获取 Store 实例 (不建议使用)](#usestore---获取-store-实例)
|
|
25
|
+
- [storeManager - 全局 Store 管理器 (推荐使用)](#storemanager---全局-store-管理器)
|
|
26
|
+
- [⚙️ 配置说明](#️-配置说明)
|
|
27
|
+
- [🎣 Hooks](#-hooks)
|
|
28
|
+
- [useAttributeMonitor - WebSocket 属性监听](#useattributemonitor---websocket-属性监听)
|
|
29
|
+
- [🌍 国际化](#-国际化)
|
|
30
|
+
- [🛠️ 工具函数](#️-工具函数)
|
|
31
|
+
- [常量定义](#常量定义)
|
|
32
|
+
- [PLATFORM_INTERNAL_APPIDS - 平台应用 ID 常量](#platform_internal_appids---平台应用-id-常量)
|
|
33
|
+
- [📋 Logger - 日志工具](#-logger---日志工具)
|
|
34
|
+
- [🖥️ Electron Preload 功能](#️-electron-preload-功能)
|
|
35
|
+
- [getMainProcessArgs - 获取主进程参数](#getmainprocessargs---获取主进程参数)
|
|
36
|
+
- [initMandatoryUVerseAPI - 初始化平台 API](#initmandatoryuverseapi---初始化平台-api)
|
|
37
|
+
- [📘 类型定义](#-类型定义)
|
|
38
|
+
- [🔌 拦截器](#-拦截器)
|
|
39
|
+
- [🔧 开发](#-开发)
|
|
40
|
+
- [📂 项目结构](#-项目结构)
|
|
41
|
+
- [🎯 使用场景](#-使用场景)
|
|
42
|
+
|
|
43
|
+
## ✨ 特性
|
|
44
|
+
|
|
45
|
+
- 🚀 **TypeScript 优先** - 完整的类型定义和智能提示
|
|
46
|
+
- 📡 **基于 Axios** - 强大的 HTTP 请求能力,支持拦截器
|
|
47
|
+
- 🔌 **Vue 插件支持** - 无缝集成 Vue 3 应用
|
|
48
|
+
- 🗄️ **响应式状态管理** - 类 Pinia 的轻量级 Store 系统,支持时间戳同步和数据同步
|
|
49
|
+
- 🌐 **WebSocket 支持** - 完整的 WebSocket 客户端,支持自动重连和 MessagePack 编解码
|
|
50
|
+
- 🌍 **国际化支持** - 完整的 vue-i18n 集成,支持中英文及自定义语言包
|
|
51
|
+
- 🎣 **Vue Composition API** - 提供常用的业务 Hooks(useAttributeMonitor 等)
|
|
52
|
+
- 🛠️ **工具函数库** - 丰富的实用工具函数(存储管理、场景检测、深拷贝、深度合并等)
|
|
53
|
+
- 🖥️ **多场景支持** - 支持浏览器、Electron BrowserWindow、Electron WebContentsView
|
|
54
|
+
- 🔇 **错误控制** - 支持通过 metadata 控制是否显示错误提示,适用于轮询和后台任务
|
|
55
|
+
- 🔌 **Electron Preload** - 提供 Preload 脚本工具函数,简化 Electron 应用开发
|
|
56
|
+
- 📦 **多格式支持** - 支持 ES Module 和 CommonJS
|
|
57
|
+
- 📝 **完整文档** - 详细的 JSDoc 注释和使用示例
|
|
58
|
+
|
|
59
|
+
## 📦 安装
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
npm install @openuverse/uvapi
|
|
63
|
+
# 或
|
|
64
|
+
yarn add @openuverse/uvapi
|
|
65
|
+
# 或
|
|
66
|
+
pnpm add @openuverse/uvapi
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Peer Dependencies
|
|
70
|
+
|
|
71
|
+
UV-API 需要以下对等依赖:
|
|
72
|
+
|
|
73
|
+
```json
|
|
74
|
+
{
|
|
75
|
+
"vue": "^3.5.0", // Vue 3 框架(必需)
|
|
76
|
+
"vue-i18n": "^11.1.12", // 国际化支持(必需,UV-API 的错误提示依赖国际化)
|
|
77
|
+
"@openuverse/rdesign": "^0.1.10" // Rigol 设计系统组件库(必需,用于消息提示)
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
**⚠️ 重要说明:**
|
|
82
|
+
- `vue-i18n` 是**必需依赖**,UV-API 在错误处理时需要使用国际化消息
|
|
83
|
+
- `@openuverse/rdesign` 是**必需依赖**,UV-API 使用其 `MessagePlugin` 组件显示错误提示
|
|
84
|
+
|
|
85
|
+
**安装所有依赖:**
|
|
86
|
+
```bash
|
|
87
|
+
npm install vue vue-i18n @openuverse/rdesign @openuverse/uvapi
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 包体积优化
|
|
91
|
+
|
|
92
|
+
UV-API 支持按需打包,显著减小体积:
|
|
93
|
+
|
|
94
|
+
**标准用法(推荐):**
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
// 继续使用现有导入方式,自动按需打包
|
|
98
|
+
import { RestAPIClient, setupI18n } from '@openuverse/uvapi'
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
**子路径导入(Electron preload 推荐):**
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
// 直接导入特定模块,体积更小
|
|
105
|
+
import { initMandatoryUVerseAPI } from '@openuverse/uvapi/preload' // ~3KB
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
**支持的子路径:** `/preload`、`/api`、`/hooks`、`/utils`、`/store`、`/locale`、`/config`
|
|
109
|
+
|
|
110
|
+
**效果:** Preload 打包体积 3-5KB(原 MB 级)
|
|
111
|
+
|
|
112
|
+
**要求:** ESM 格式(Node.js 14+、Vite/Webpack 5+)
|
|
113
|
+
|
|
114
|
+
## 🚀 快速开始
|
|
115
|
+
|
|
116
|
+
### Vue 插件方式(推荐)
|
|
117
|
+
|
|
118
|
+
**⚠️ 重要:国际化插件必须在 UV-API 插件之前注册!**
|
|
119
|
+
|
|
120
|
+
UV-API 依赖 vue-i18n 进行错误消息的国际化显示,因此必须按照以下顺序初始化:
|
|
121
|
+
|
|
122
|
+
```typescript
|
|
123
|
+
import { createApp } from 'vue'
|
|
124
|
+
import RigolUVAPI, { setupI18n } from '@openuverse/uvapi'
|
|
125
|
+
import App from './App.vue'
|
|
126
|
+
|
|
127
|
+
const app = createApp(App)
|
|
128
|
+
|
|
129
|
+
// 1. 初始化国际化(必需步骤)
|
|
130
|
+
const i18n = setupI18n({
|
|
131
|
+
locale: 'zh-CN', // 设置默认语言
|
|
132
|
+
messages: {
|
|
133
|
+
'zh-CN': {
|
|
134
|
+
app: {
|
|
135
|
+
title: '我的应用'
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
'en-US': {
|
|
139
|
+
app: {
|
|
140
|
+
title: 'My App'
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
// 2. 注册国际化插件(必须在 UV-API 之前)
|
|
147
|
+
app.use(i18n)
|
|
148
|
+
|
|
149
|
+
// 3. 注册 Rigol UV API 插件
|
|
150
|
+
app.use(RigolUVAPI, {
|
|
151
|
+
appId: 'your-app-id'
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
app.mount('#app')
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
**插件注册顺序说明:**
|
|
158
|
+
1. ✅ 先注册 `i18n` 插件
|
|
159
|
+
2. ✅ 再注册 `RigolUVAPI` 插件
|
|
160
|
+
3. ❌ 不能颠倒顺序,否则 UV-API 的错误提示功能将无法正常工作
|
|
161
|
+
|
|
162
|
+
### 直接使用方式
|
|
163
|
+
|
|
164
|
+
**💡 推荐做法:使用扫描工具自动生成 API 客户端**
|
|
165
|
+
|
|
166
|
+
- `UserClient` 和 `TaskClient` 仅作为**示例**,展示如何继承 RestAPIClient 创建业务客户端
|
|
167
|
+
- **推荐做法**:使用扫描工具对后端接口进行扫描,自动生成类型完整的 API 客户端类
|
|
168
|
+
- 对于临时调用或简单场景,也可以直接使用 `RestAPIClient` 的业务方法(`action`)
|
|
169
|
+
|
|
170
|
+
#### 推荐方式:使用 RestAPIClient
|
|
171
|
+
|
|
172
|
+
```typescript
|
|
173
|
+
import { RestAPIClient } from '@openuverse/uvapi'
|
|
174
|
+
|
|
175
|
+
// 创建 REST API 客户端
|
|
176
|
+
const apiClient = new RestAPIClient({
|
|
177
|
+
baseURL: 'https://api.example.com',
|
|
178
|
+
timeout: 10000,
|
|
179
|
+
apiVersion: 'v1',
|
|
180
|
+
workerId: 'your-worker-id',
|
|
181
|
+
urlType: 'header',
|
|
182
|
+
headers: {
|
|
183
|
+
'Authorization': 'Bearer your-token'
|
|
184
|
+
}
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
// 调用业务接口
|
|
188
|
+
const response = await apiClient.action('get_users')
|
|
189
|
+
const result = response.result // 获取实际数据
|
|
190
|
+
|
|
191
|
+
console.log(response.status) // 'success'
|
|
192
|
+
console.log(response.result) // 实际的用户数据
|
|
193
|
+
console.log(response.timestamp) // 时间戳
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
**💡 关于返回值:**
|
|
197
|
+
- 所有 API 方法返回 `Promise<Response<T>>`
|
|
198
|
+
- 通过 `response.result` 访问实际业务数据
|
|
199
|
+
- 失败时会抛出 `ErrorResponse` 异常
|
|
200
|
+
|
|
201
|
+
```typescript
|
|
202
|
+
// 正确的使用方式
|
|
203
|
+
const response = await apiClient.action<UserList>('get_users')
|
|
204
|
+
const users = response.result // users 类型为 UserList
|
|
205
|
+
|
|
206
|
+
// 错误处理
|
|
207
|
+
try {
|
|
208
|
+
const response = await apiClient.action('some_action')
|
|
209
|
+
console.log(response.result)
|
|
210
|
+
} catch (error: any) {
|
|
211
|
+
if (error.status === 'error') {
|
|
212
|
+
console.error('错误:', error.message)
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
#### 示例:UserClient 和 TaskClient(仅供参考)
|
|
218
|
+
|
|
219
|
+
以下客户端仅作为示例,展示如何扩展 RestAPIClient:
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
import { UserClient, TaskClient } from '@openuverse/uvapi'
|
|
223
|
+
|
|
224
|
+
// 示例:用户客户端(实际项目中请使用 RestAPIClient)
|
|
225
|
+
const userClient = new UserClient({
|
|
226
|
+
baseURL: 'https://api.example.com',
|
|
227
|
+
timeout: 10000
|
|
228
|
+
})
|
|
229
|
+
|
|
230
|
+
// 示例:任务客户端(实际项目中请使用 RestAPIClient)
|
|
231
|
+
const taskClient = new TaskClient({
|
|
232
|
+
baseURL: 'https://api.example.com',
|
|
233
|
+
timeout: 10000
|
|
234
|
+
})
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
## 📚 API 文档
|
|
238
|
+
|
|
239
|
+
**💡 推荐做法:使用扫描工具自动生成 API 客户端**
|
|
240
|
+
|
|
241
|
+
- `UserClient` 和 `TaskClient` 仅作为**示例参考**,展示如何继承 RestAPIClient
|
|
242
|
+
- **推荐做法**:使用扫描工具对后端接口进行扫描,自动生成类型完整的 API 客户端类
|
|
243
|
+
- 对于临时调用或简单场景,可以使用 `RestAPIClient` 的 `action` 方法
|
|
244
|
+
|
|
245
|
+
**核心业务方法:**
|
|
246
|
+
- `action` - 执行业务操作(主要使用方法)
|
|
247
|
+
|
|
248
|
+
**⚠️ 注意:** `getAttribute`、`setAttribute`、`getAttributes`、`setAttributes` 这 4 个属性相关方法暂时不开放在 UI 中使用。
|
|
249
|
+
|
|
250
|
+
详细说明请参见 [RestAPIClient 章节](#restapiclient---rest-api-基础客户端)。
|
|
251
|
+
|
|
252
|
+
---
|
|
253
|
+
|
|
254
|
+
### UserClient - 用户管理(示例参考)
|
|
255
|
+
|
|
256
|
+
> 📝 **说明:** 此客户端仅作为示例,展示如何继承 RestAPIClient。实际项目中请直接使用 RestAPIClient。
|
|
257
|
+
|
|
258
|
+
#### 创建实例
|
|
259
|
+
|
|
260
|
+
```typescript
|
|
261
|
+
import { UserClient } from '@openuverse/uvapi'
|
|
262
|
+
|
|
263
|
+
const userClient = new UserClient({
|
|
264
|
+
baseURL: 'https://api.example.com',
|
|
265
|
+
timeout: 5000,
|
|
266
|
+
headers: {
|
|
267
|
+
'Authorization': 'Bearer token123'
|
|
268
|
+
}
|
|
269
|
+
})
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
#### API 方法
|
|
273
|
+
|
|
274
|
+
##### 1. create_user - 创建新用户
|
|
275
|
+
|
|
276
|
+
```typescript
|
|
277
|
+
const response = await userClient.create_user({
|
|
278
|
+
name: '张三',
|
|
279
|
+
email: 'zhangsan@example.com',
|
|
280
|
+
age: 25 // 可选参数
|
|
281
|
+
})
|
|
282
|
+
const newUser = response.result // 获取实际用户对象
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
**参数说明:**
|
|
286
|
+
- `name` (string, 必填) - 用户名称
|
|
287
|
+
- `email` (string, 必填) - 用户邮箱
|
|
288
|
+
- `age` (number, 可选) - 用户年龄
|
|
289
|
+
|
|
290
|
+
**返回值:** `Promise<Response<User>>` - 包含用户对象的响应
|
|
291
|
+
|
|
292
|
+
---
|
|
293
|
+
|
|
294
|
+
##### 2. get_users - 获取所有用户列表
|
|
295
|
+
|
|
296
|
+
```typescript
|
|
297
|
+
const response = await userClient.get_users()
|
|
298
|
+
const users = response.result // 获取实际用户列表
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
**返回值:** `Promise<Response<User[]>>` - 包含用户列表的响应
|
|
302
|
+
|
|
303
|
+
---
|
|
304
|
+
|
|
305
|
+
##### 3. get_user - 获取单个用户信息
|
|
306
|
+
|
|
307
|
+
```typescript
|
|
308
|
+
const response = await userClient.get_user({
|
|
309
|
+
user_id: 1
|
|
310
|
+
})
|
|
311
|
+
const user = response.result // 获取实际用户对象
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
**参数说明:**
|
|
315
|
+
- `user_id` (number, 必填) - 用户 ID
|
|
316
|
+
|
|
317
|
+
**返回值:** `Promise<Response<User>>` - 包含用户对象的响应
|
|
318
|
+
|
|
319
|
+
---
|
|
320
|
+
|
|
321
|
+
##### 4. update_user - 更新用户信息
|
|
322
|
+
|
|
323
|
+
```typescript
|
|
324
|
+
const response = await userClient.update_user({
|
|
325
|
+
user_id: 1,
|
|
326
|
+
user_update: {
|
|
327
|
+
name: '张三(已更新)',
|
|
328
|
+
email: 'zhangsan_new@example.com',
|
|
329
|
+
age: 26
|
|
330
|
+
}
|
|
331
|
+
})
|
|
332
|
+
const updatedUser = response.result // 获取更新后的用户对象
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
**参数说明:**
|
|
336
|
+
- `user_id` (number, 必填) - 用户 ID
|
|
337
|
+
- `user_update` (object, 必填) - 用户更新信息对象
|
|
338
|
+
- `name` (string, 可选) - 用户名称
|
|
339
|
+
- `email` (string, 可选) - 用户邮箱
|
|
340
|
+
- `age` (number, 可选) - 用户年龄
|
|
341
|
+
|
|
342
|
+
**返回值:** `Promise<Response<User>>` - 包含更新后用户对象的响应
|
|
343
|
+
|
|
344
|
+
---
|
|
345
|
+
|
|
346
|
+
##### 5. delete_user - 删除用户
|
|
347
|
+
|
|
348
|
+
```typescript
|
|
349
|
+
const response = await userClient.delete_user({
|
|
350
|
+
id: 1
|
|
351
|
+
})
|
|
352
|
+
const deletedUser = response.result // 获取被删除的用户对象
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
**参数说明:**
|
|
356
|
+
- `id` (number, 必填) - 要删除的用户 ID
|
|
357
|
+
|
|
358
|
+
**返回值:** `Promise<Response<User>>` - 包含被删除用户对象的响应
|
|
359
|
+
|
|
360
|
+
---
|
|
361
|
+
|
|
362
|
+
### TaskClient - 任务管理(示例参考)
|
|
363
|
+
|
|
364
|
+
> 📝 **说明:** 此客户端仅作为示例,展示如何继承 RestAPIClient。实际项目中请直接使用 RestAPIClient。
|
|
365
|
+
|
|
366
|
+
#### 创建实例
|
|
367
|
+
|
|
368
|
+
```typescript
|
|
369
|
+
import { TaskClient } from '@openuverse/uvapi'
|
|
370
|
+
|
|
371
|
+
const taskClient = new TaskClient({
|
|
372
|
+
baseURL: 'https://api.example.com',
|
|
373
|
+
timeout: 5000,
|
|
374
|
+
headers: {
|
|
375
|
+
'Authorization': 'Bearer token123'
|
|
376
|
+
}
|
|
377
|
+
})
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
#### API 方法
|
|
381
|
+
|
|
382
|
+
##### 1. create_task - 创建新任务
|
|
383
|
+
|
|
384
|
+
```typescript
|
|
385
|
+
const response = await taskClient.create_task({
|
|
386
|
+
title: '完成项目文档',
|
|
387
|
+
description: '编写 API 接口文档',
|
|
388
|
+
completed: false,
|
|
389
|
+
priority: 1,
|
|
390
|
+
user_id: 123
|
|
391
|
+
})
|
|
392
|
+
const newTask = response.result // 获取实际任务对象
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
**参数说明:**
|
|
396
|
+
- `title` (string, 必填) - 任务标题
|
|
397
|
+
- `description` (string, 可选) - 任务描述
|
|
398
|
+
- `completed` (boolean, 可选) - 任务完成状态
|
|
399
|
+
- `priority` (1 | 2 | 3 | 4 | 5, 可选) - 任务优先级,1-5
|
|
400
|
+
- `user_id` (number, 可选) - 关联的用户 ID
|
|
401
|
+
|
|
402
|
+
**返回值:** `Promise<Response<Task>>` - 包含任务对象的响应
|
|
403
|
+
|
|
404
|
+
---
|
|
405
|
+
|
|
406
|
+
##### 2. get_tasks - 获取所有任务列表
|
|
407
|
+
|
|
408
|
+
```typescript
|
|
409
|
+
const response = await taskClient.get_tasks()
|
|
410
|
+
const tasks = response.result // 获取实际任务列表
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
**返回值:** `Promise<Response<Task[]>>` - 包含任务列表的响应
|
|
414
|
+
|
|
415
|
+
---
|
|
416
|
+
|
|
417
|
+
##### 3. get_task - 获取单个任务信息
|
|
418
|
+
|
|
419
|
+
```typescript
|
|
420
|
+
const response = await taskClient.get_task({
|
|
421
|
+
task_id: 1
|
|
422
|
+
})
|
|
423
|
+
const task = response.result // 获取实际任务对象
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
**参数说明:**
|
|
427
|
+
- `task_id` (number, 必填) - 任务 ID
|
|
428
|
+
|
|
429
|
+
**返回值:** `Promise<Response<Task>>` - 包含任务对象的响应
|
|
430
|
+
|
|
431
|
+
---
|
|
432
|
+
|
|
433
|
+
##### 4. update_task - 更新任务信息
|
|
434
|
+
|
|
435
|
+
```typescript
|
|
436
|
+
const response = await taskClient.update_task({
|
|
437
|
+
task_id: 1,
|
|
438
|
+
task_update: {
|
|
439
|
+
title: '完成项目文档(已更新)',
|
|
440
|
+
description: '编写完整的 API 接口文档',
|
|
441
|
+
completed: true,
|
|
442
|
+
priority: 2,
|
|
443
|
+
user_id: 456
|
|
444
|
+
}
|
|
445
|
+
})
|
|
446
|
+
const updatedTask = response.result // 获取更新后的任务对象
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
**参数说明:**
|
|
450
|
+
- `task_id` (number, 必填) - 任务 ID
|
|
451
|
+
- `task_update` (object, 必填) - 任务更新信息对象
|
|
452
|
+
- `title` (string, 可选) - 任务标题
|
|
453
|
+
- `description` (string, 可选) - 任务描述
|
|
454
|
+
- `completed` (boolean, 可选) - 任务完成状态
|
|
455
|
+
- `priority` (1 | 2 | 3 | 4 | 5, 可选) - 任务优先级,1-5
|
|
456
|
+
- `user_id` (number, 可选) - 关联的用户 ID
|
|
457
|
+
|
|
458
|
+
**返回值:** `Promise<Response<Task>>` - 包含更新后任务对象的响应
|
|
459
|
+
|
|
460
|
+
---
|
|
461
|
+
|
|
462
|
+
##### 5. delete_task - 删除任务
|
|
463
|
+
|
|
464
|
+
```typescript
|
|
465
|
+
const response = await taskClient.delete_task({
|
|
466
|
+
id: 1
|
|
467
|
+
})
|
|
468
|
+
const deletedTask = response.result // 获取被删除的任务对象
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
**参数说明:**
|
|
472
|
+
- `id` (number, 必填) - 要删除的任务 ID
|
|
473
|
+
|
|
474
|
+
**返回值:** `Promise<Response<Task>>` - 包含被删除任务对象的响应
|
|
475
|
+
|
|
476
|
+
---
|
|
477
|
+
|
|
478
|
+
### RestAPIClient - REST API 基础客户端
|
|
479
|
+
|
|
480
|
+
`RestAPIClient` 是所有业务客户端的基类,提供了统一的 HTTP 请求封装和业务接口调用方式。
|
|
481
|
+
|
|
482
|
+
**💡 推荐做法:使用扫描工具自动生成 API 客户端**
|
|
483
|
+
|
|
484
|
+
- **最佳实践**:使用扫描工具对后端接口进行扫描,自动生成类型完整的 API 客户端类
|
|
485
|
+
- **临时方案**:对于临时调用或简单场景,可以使用 `RestAPIClient` 的 `action` 方法
|
|
486
|
+
- **继承扩展**:您也可以继承它创建自定义的业务客户端(参考 UserClient、TaskClient 示例)
|
|
487
|
+
- ⚠️ **属性方法暂不开放**:`getAttribute`、`setAttribute`、`getAttributes`、`setAttributes` 这 4 个属性相关方法暂时不开放在 UI 中使用
|
|
488
|
+
|
|
489
|
+
#### 创建实例
|
|
490
|
+
|
|
491
|
+
```typescript
|
|
492
|
+
import { RestAPIClient } from '@openuverse/uvapi'
|
|
493
|
+
|
|
494
|
+
const apiClient = new RestAPIClient({
|
|
495
|
+
baseURL: 'https://api.example.com',
|
|
496
|
+
timeout: 10000,
|
|
497
|
+
apiVersion: 'v1', // API 版本,默认 'v1'
|
|
498
|
+
workerId: 'your-worker-id', // Worker ID
|
|
499
|
+
urlType: 'header', // URL 类型:'path' 或 'header',默认 'header'
|
|
500
|
+
headers: {
|
|
501
|
+
'Authorization': 'Bearer token123',
|
|
502
|
+
'X-Custom-Header': 'custom-value'
|
|
503
|
+
}
|
|
504
|
+
})
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
**配置说明:**
|
|
508
|
+
- `baseURL` - API 基础 URL
|
|
509
|
+
- `timeout` - 请求超时时间(毫秒)
|
|
510
|
+
- `apiVersion` - API 版本号,默认 'v1'
|
|
511
|
+
- `workerId` - Worker ID,用于标识不同的业务模块
|
|
512
|
+
- `urlType` - URL 类型,支持 'path' 和 'header' 两种方式
|
|
513
|
+
- `path` 模式:URL 格式为 `/{apiVersion}/workers/{workerId}`
|
|
514
|
+
- `header` 模式:通过请求头 `X-UV-API-Version` 和 `X-UV-Worker-ID` 传递
|
|
515
|
+
- `headers` - 自定义请求头
|
|
516
|
+
|
|
517
|
+
#### 基础 HTTP 方法 (尽量避免使用)
|
|
518
|
+
|
|
519
|
+
RestAPIClient 提供了标准的 HTTP 请求方法,支持完整的 TypeScript 类型推断。
|
|
520
|
+
|
|
521
|
+
##### 1. GET 请求
|
|
522
|
+
|
|
523
|
+
```typescript
|
|
524
|
+
// 基础 GET 请求
|
|
525
|
+
const data = await apiClient.get('/api/users')
|
|
526
|
+
|
|
527
|
+
// 带查询参数的 GET 请求
|
|
528
|
+
const users = await apiClient.get<User[]>('/api/users', {
|
|
529
|
+
params: {
|
|
530
|
+
page: 1,
|
|
531
|
+
pageSize: 10,
|
|
532
|
+
status: 'active'
|
|
533
|
+
}
|
|
534
|
+
})
|
|
535
|
+
|
|
536
|
+
// 带自定义请求头的 GET 请求
|
|
537
|
+
const user = await apiClient.get<User>('/api/users/123', {
|
|
538
|
+
headers: {
|
|
539
|
+
'X-Custom-Header': 'value'
|
|
540
|
+
}
|
|
541
|
+
})
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
##### 2. POST 请求
|
|
545
|
+
|
|
546
|
+
```typescript
|
|
547
|
+
// 基础 POST 请求
|
|
548
|
+
const newUser = await apiClient.post<User>('/api/users', {
|
|
549
|
+
name: '张三',
|
|
550
|
+
email: 'zhangsan@example.com'
|
|
551
|
+
})
|
|
552
|
+
|
|
553
|
+
// 带类型推断的 POST 请求
|
|
554
|
+
interface CreateUserRequest {
|
|
555
|
+
name: string
|
|
556
|
+
email: string
|
|
557
|
+
age?: number
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
interface CreateUserResponse {
|
|
561
|
+
id: number
|
|
562
|
+
name: string
|
|
563
|
+
email: string
|
|
564
|
+
created_at: string
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
const response = await apiClient.post<CreateUserResponse, CreateUserRequest>(
|
|
568
|
+
'/api/users',
|
|
569
|
+
{
|
|
570
|
+
name: '李四',
|
|
571
|
+
email: 'lisi@example.com',
|
|
572
|
+
age: 25
|
|
573
|
+
}
|
|
574
|
+
)
|
|
575
|
+
|
|
576
|
+
// 带自定义配置的 POST 请求
|
|
577
|
+
const result = await apiClient.post('/api/upload', formData, {
|
|
578
|
+
headers: {
|
|
579
|
+
'Content-Type': 'multipart/form-data'
|
|
580
|
+
},
|
|
581
|
+
timeout: 30000
|
|
582
|
+
})
|
|
583
|
+
```
|
|
584
|
+
|
|
585
|
+
##### 3. PUT 请求
|
|
586
|
+
|
|
587
|
+
```typescript
|
|
588
|
+
// 更新资源
|
|
589
|
+
const updatedUser = await apiClient.put<User>('/api/users/123', {
|
|
590
|
+
name: '张三(已更新)',
|
|
591
|
+
email: 'zhangsan_new@example.com'
|
|
592
|
+
})
|
|
593
|
+
|
|
594
|
+
// 带类型的 PUT 请求
|
|
595
|
+
interface UpdateUserRequest {
|
|
596
|
+
name?: string
|
|
597
|
+
email?: string
|
|
598
|
+
age?: number
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
const user = await apiClient.put<User, UpdateUserRequest>(
|
|
602
|
+
'/api/users/123',
|
|
603
|
+
{
|
|
604
|
+
name: '王五',
|
|
605
|
+
age: 30
|
|
606
|
+
}
|
|
607
|
+
)
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
##### 4. DELETE 请求
|
|
611
|
+
|
|
612
|
+
```typescript
|
|
613
|
+
// 删除资源
|
|
614
|
+
const deletedUser = await apiClient.delete<User>('/api/users/123')
|
|
615
|
+
|
|
616
|
+
// 带查询参数的 DELETE 请求
|
|
617
|
+
await apiClient.delete('/api/users/123', {
|
|
618
|
+
params: {
|
|
619
|
+
force: true
|
|
620
|
+
}
|
|
621
|
+
})
|
|
622
|
+
```
|
|
623
|
+
|
|
624
|
+
##### 5. request 通用方法
|
|
625
|
+
|
|
626
|
+
```typescript
|
|
627
|
+
// 使用 request 方法发起任意类型的 HTTP 请求
|
|
628
|
+
const response = await apiClient.request<ResponseType>({
|
|
629
|
+
method: 'PATCH',
|
|
630
|
+
url: '/api/users/123',
|
|
631
|
+
data: {
|
|
632
|
+
status: 'active'
|
|
633
|
+
},
|
|
634
|
+
headers: {
|
|
635
|
+
'X-Custom-Header': 'value'
|
|
636
|
+
}
|
|
637
|
+
})
|
|
638
|
+
|
|
639
|
+
// 发起带认证的请求
|
|
640
|
+
const data = await apiClient.request({
|
|
641
|
+
method: 'GET',
|
|
642
|
+
url: '/api/protected-resource',
|
|
643
|
+
headers: {
|
|
644
|
+
'Authorization': 'Bearer your-token'
|
|
645
|
+
}
|
|
646
|
+
})
|
|
647
|
+
```
|
|
648
|
+
|
|
649
|
+
#### 业务接口方法
|
|
650
|
+
|
|
651
|
+
**💡 推荐做法:使用扫描工具自动生成 API 客户端**
|
|
652
|
+
|
|
653
|
+
各预置 APP 的后台接口暂未集成到 UV-API 中。**推荐使用扫描工具对后端接口进行扫描,自动生成类型完整的 API 客户端类**。
|
|
654
|
+
|
|
655
|
+
**可用的业务方法:**
|
|
656
|
+
1. **`action`** - 执行业务操作(主要使用方法)
|
|
657
|
+
|
|
658
|
+
**⚠️ 暂不开放的方法:**
|
|
659
|
+
- `getAttribute` - 获取单个属性(暂不开放在 UI 中使用)
|
|
660
|
+
- `setAttribute` - 设置单个属性(暂不开放在 UI 中使用)
|
|
661
|
+
- `getAttributes` - 获取所有属性(暂不开放在 UI 中使用)
|
|
662
|
+
- `setAttributes` - 批量设置属性(暂不开放在 UI 中使用)
|
|
663
|
+
|
|
664
|
+
##### 1. action - 执行业务操作(⭐ 最常用)
|
|
665
|
+
|
|
666
|
+
**这是最重要和最常用的业务方法!**
|
|
667
|
+
|
|
668
|
+
`action` 方法用于向后端 Worker 发送业务请求,是调用后端接口的主要方式。
|
|
669
|
+
|
|
670
|
+
**使用场景:**
|
|
671
|
+
- 调用后端的业务 action(如 `get_user_list`、`create_order`、`update_status` 等)
|
|
672
|
+
- 执行任何业务逻辑操作
|
|
673
|
+
- 获取或提交业务数据
|
|
674
|
+
|
|
675
|
+
**方法签名:**
|
|
676
|
+
```typescript
|
|
677
|
+
action<T = any, D = any>(
|
|
678
|
+
actionName: string,
|
|
679
|
+
data?: D,
|
|
680
|
+
config?: AxiosRequestConfig
|
|
681
|
+
): Promise<Response<T>>
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
**响应格式:**
|
|
685
|
+
```typescript
|
|
686
|
+
interface Response<T> {
|
|
687
|
+
status: 'success'
|
|
688
|
+
result: T // 实际业务数据
|
|
689
|
+
timestamp: string | number
|
|
690
|
+
}
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
**使用示例:**
|
|
694
|
+
|
|
695
|
+
```typescript
|
|
696
|
+
// 基础 action 调用
|
|
697
|
+
const response = await apiClient.action('get_user_list')
|
|
698
|
+
console.log(response.status) // 'success'
|
|
699
|
+
console.log(response.result) // 实际的用户列表数据
|
|
700
|
+
console.log(response.timestamp) // 时间戳
|
|
701
|
+
|
|
702
|
+
// 带参数的 action 调用
|
|
703
|
+
const response = await apiClient.action('get_user', {
|
|
704
|
+
user_id: 123
|
|
705
|
+
})
|
|
706
|
+
const user = response.result // 获取实际数据
|
|
707
|
+
|
|
708
|
+
// 带类型推断的 action 调用
|
|
709
|
+
interface GetUserRequest {
|
|
710
|
+
user_id: number
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
interface User {
|
|
714
|
+
id: number
|
|
715
|
+
name: string
|
|
716
|
+
email: string
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
const response = await apiClient.action<User, GetUserRequest>(
|
|
720
|
+
'get_user',
|
|
721
|
+
{ user_id: 123 }
|
|
722
|
+
)
|
|
723
|
+
// response 类型为 Response<User>
|
|
724
|
+
const user = response.result // user 类型为 User
|
|
725
|
+
|
|
726
|
+
// 带自定义配置的 action 调用
|
|
727
|
+
const response = await apiClient.action(
|
|
728
|
+
'process_data',
|
|
729
|
+
{ data: largeData },
|
|
730
|
+
{
|
|
731
|
+
timeout: 60000, // 自定义超时时间
|
|
732
|
+
headers: {
|
|
733
|
+
'X-Priority': 'high'
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
)
|
|
737
|
+
const processedData = response.result
|
|
738
|
+
```
|
|
739
|
+
|
|
740
|
+
**工作原理:**
|
|
741
|
+
- `action` 方法会根据 `urlType` 配置自动构建请求 URL:
|
|
742
|
+
- `urlType: 'header'` 模式:`{baseURL}/workers/{actionName}`
|
|
743
|
+
- `urlType: 'path'` 模式:`{baseURL}/{apiVersion}/workers/{workerId}/{actionName}`
|
|
744
|
+
- `header` 模式下会在请求头中设置 `X-UV-API-Version` 和 `X-UV-Worker-ID`
|
|
745
|
+
- 所有参数通过 POST 方法发送到后端
|
|
746
|
+
|
|
747
|
+
**实际使用示例:**
|
|
748
|
+
|
|
749
|
+
```typescript
|
|
750
|
+
// 示例 1:获取数据列表
|
|
751
|
+
const response = await apiClient.action('get_user_list', {
|
|
752
|
+
page: 1,
|
|
753
|
+
pageSize: 20,
|
|
754
|
+
status: 'active'
|
|
755
|
+
})
|
|
756
|
+
const users = response.result // 获取实际数据
|
|
757
|
+
|
|
758
|
+
// 示例 2:创建数据
|
|
759
|
+
const response2 = await apiClient.action('create_order', {
|
|
760
|
+
productId: 123,
|
|
761
|
+
quantity: 2,
|
|
762
|
+
price: 99.99
|
|
763
|
+
})
|
|
764
|
+
const newOrder = response2.result
|
|
765
|
+
|
|
766
|
+
// 示例 3:更新数据
|
|
767
|
+
const response3 = await apiClient.action('update_order_status', {
|
|
768
|
+
orderId: 456,
|
|
769
|
+
status: 'shipped',
|
|
770
|
+
trackingNumber: 'ABC123'
|
|
771
|
+
})
|
|
772
|
+
const updated = response3.result
|
|
773
|
+
|
|
774
|
+
// 示例 4:删除数据
|
|
775
|
+
const response4 = await apiClient.action('delete_order', {
|
|
776
|
+
orderId: 789
|
|
777
|
+
})
|
|
778
|
+
console.log(response4.status) // 'success'
|
|
779
|
+
|
|
780
|
+
// 示例 5:复杂业务操作
|
|
781
|
+
const response5 = await apiClient.action('process_batch_operation', {
|
|
782
|
+
operation: 'export',
|
|
783
|
+
filters: {
|
|
784
|
+
dateRange: ['2024-01-01', '2024-12-31'],
|
|
785
|
+
category: 'electronics'
|
|
786
|
+
},
|
|
787
|
+
format: 'xlsx'
|
|
788
|
+
})
|
|
789
|
+
const result = response5.result
|
|
790
|
+
```
|
|
791
|
+
|
|
792
|
+
**返回值结构说明:**
|
|
793
|
+
- `action` 返回 `Promise<Response<T>>`,其中 `T` 是 `result` 字段的类型
|
|
794
|
+
- 需要通过 `response.result` 访问实际业务数据
|
|
795
|
+
- `response.status` 始终为 `'success'`(失败时会抛出异常)
|
|
796
|
+
- `response.timestamp` 包含服务器响应的时间戳
|
|
797
|
+
|
|
798
|
+
**最佳实践:**
|
|
799
|
+
- ✅ 使用 TypeScript 类型定义请求和响应数据
|
|
800
|
+
- ✅ 通过 `response.result` 访问实际数据
|
|
801
|
+
- ✅ 对于长时间运行的操作,使用自定义 timeout
|
|
802
|
+
- ✅ 为关键操作添加错误处理
|
|
803
|
+
- ✅ 使用语义化的 action 名称(如 `get_*`、`create_*`、`update_*`、`delete_*`)
|
|
804
|
+
|
|
805
|
+
---
|
|
806
|
+
|
|
807
|
+
**业务方法使用总结:**
|
|
808
|
+
|
|
809
|
+
| 方法 | 用途 | 状态 |
|
|
810
|
+
|------|------|------|
|
|
811
|
+
| `action` | 执行业务操作 | ✅ 可用(主要使用) |
|
|
812
|
+
| `getAttribute` | 获取单个属性 | ⚠️ 暂不开放 |
|
|
813
|
+
| `setAttribute` | 设置单个属性 | ⚠️ 暂不开放 |
|
|
814
|
+
| `getAttributes` | 获取所有属性 | ⚠️ 暂不开放 |
|
|
815
|
+
| `setAttributes` | 批量设置属性 | ⚠️ 暂不开放 |
|
|
816
|
+
|
|
817
|
+
**推荐使用模式:**
|
|
818
|
+
```typescript
|
|
819
|
+
// ✅ 推荐:使用扫描工具自动生成 API 客户端
|
|
820
|
+
// 扫描工具会根据后端接口定义自动生成类型完整的客户端类
|
|
821
|
+
|
|
822
|
+
// ✅ 临时方案:使用 action 方法进行业务操作
|
|
823
|
+
const response1 = await apiClient.action('get_data_list', { page: 1 })
|
|
824
|
+
const data = response1.result // 访问实际数据
|
|
825
|
+
|
|
826
|
+
const response2 = await apiClient.action('get_user', { user_id: 123 })
|
|
827
|
+
const user = response2.result
|
|
828
|
+
|
|
829
|
+
const response3 = await apiClient.action('update_status', { status: 'active' })
|
|
830
|
+
const result = response3.result
|
|
831
|
+
```
|
|
832
|
+
|
|
833
|
+
**⚠️ 注意:** `getAttribute`、`setAttribute`、`getAttributes`、`setAttributes` 这 4 个属性相关方法暂时不开放在 UI 中使用,文档中不再提供详细说明。
|
|
834
|
+
|
|
835
|
+
---
|
|
836
|
+
|
|
837
|
+
#### 继承 RestAPIClient 创建自定义客户端(参考)
|
|
838
|
+
|
|
839
|
+
RestAPIClient 采用面向对象设计,您可以继承它来创建自定义的业务客户端。
|
|
840
|
+
|
|
841
|
+
##### 示例:创建产品管理客户端
|
|
842
|
+
|
|
843
|
+
```typescript
|
|
844
|
+
import { RestAPIClient, RestAPIConfig } from '@openuverse/uvapi'
|
|
845
|
+
|
|
846
|
+
// 定义产品类型
|
|
847
|
+
interface Product {
|
|
848
|
+
id: number
|
|
849
|
+
name: string
|
|
850
|
+
price: number
|
|
851
|
+
stock: number
|
|
852
|
+
category: string
|
|
853
|
+
created_at: string
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// 继承 RestAPIClient 创建 ProductClient
|
|
857
|
+
class ProductClient extends RestAPIClient {
|
|
858
|
+
constructor(config?: Omit<RestAPIConfig, 'workerId'>) {
|
|
859
|
+
super({
|
|
860
|
+
workerId: 'product-service', // 指定 Worker ID
|
|
861
|
+
...config
|
|
862
|
+
})
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// 使用 action 方法封装业务接口
|
|
866
|
+
// 方式1:直接返回 Response<T>
|
|
867
|
+
async getProducts(): Promise<Response<Product[]>> {
|
|
868
|
+
return this.action<Product[]>('get_products')
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// 方式2:解包 result,返回实际数据(推荐)
|
|
872
|
+
async getProduct(id: number): Promise<Product> {
|
|
873
|
+
const response = await this.action<Product>('get_product', { product_id: id })
|
|
874
|
+
return response.result
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
async createProduct(data: Omit<Product, 'id' | 'created_at'>): Promise<Product> {
|
|
878
|
+
const response = await this.action<Product>('create_product', data)
|
|
879
|
+
return response.result
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
async updateProduct(id: number, data: Partial<Product>): Promise<Product> {
|
|
883
|
+
const response = await this.action<Product>('update_product', {
|
|
884
|
+
product_id: id,
|
|
885
|
+
product_update: data
|
|
886
|
+
})
|
|
887
|
+
return response.result
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
async deleteProduct(id: number): Promise<void> {
|
|
891
|
+
const response = await this.action<void>('delete_product', { product_id: id })
|
|
892
|
+
return response.result
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// 也可以直接使用 HTTP 方法
|
|
896
|
+
async searchProducts(keyword: string): Promise<Product[]> {
|
|
897
|
+
const response = await this.get<Product[]>(`${this.baseURL}/search`, {
|
|
898
|
+
params: { keyword }
|
|
899
|
+
})
|
|
900
|
+
return response.result
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
// ⚠️ 属性方法暂不开放使用
|
|
904
|
+
// async getProductConfig() {
|
|
905
|
+
// return this.getAttribute('product_config')
|
|
906
|
+
// }
|
|
907
|
+
|
|
908
|
+
// async updateProductConfig(config: any) {
|
|
909
|
+
// return this.setAttribute('product_config', config)
|
|
910
|
+
// }
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
// 使用自定义客户端
|
|
914
|
+
const productClient = new ProductClient({
|
|
915
|
+
baseURL: 'https://api.example.com',
|
|
916
|
+
timeout: 10000
|
|
917
|
+
})
|
|
918
|
+
|
|
919
|
+
// 调用业务方法
|
|
920
|
+
const products = await productClient.getProducts()
|
|
921
|
+
const product = await productClient.getProduct(123)
|
|
922
|
+
const newProduct = await productClient.createProduct({
|
|
923
|
+
name: 'New Product',
|
|
924
|
+
price: 99.99,
|
|
925
|
+
stock: 100,
|
|
926
|
+
category: 'Electronics'
|
|
927
|
+
})
|
|
928
|
+
```
|
|
929
|
+
|
|
930
|
+
#### 拦截器和错误处理
|
|
931
|
+
|
|
932
|
+
RestAPIClient 内置了请求和响应拦截器,提供统一的错误处理。
|
|
933
|
+
|
|
934
|
+
##### 错误处理
|
|
935
|
+
|
|
936
|
+
UV-API 内置了完整的错误处理机制,会自动捕获并显示错误提示。
|
|
937
|
+
|
|
938
|
+
**错误类型:**
|
|
939
|
+
|
|
940
|
+
```typescript
|
|
941
|
+
interface ErrorResponse<T> {
|
|
942
|
+
status: 'error'
|
|
943
|
+
code: string // 错误代码(如 'UNAUTHORIZED', 'NOT_FOUND' 等)
|
|
944
|
+
error_tpye: string // 错误类型(如 'HTTP_ERROR', 'NETWORK_ERROR' 等)
|
|
945
|
+
message: string // 国际化的错误消息
|
|
946
|
+
timestamp: string | number
|
|
947
|
+
result?: T
|
|
948
|
+
originError?: Error // 原始错误对象
|
|
949
|
+
}
|
|
950
|
+
```
|
|
951
|
+
|
|
952
|
+
**错误处理示例:**
|
|
953
|
+
|
|
954
|
+
```typescript
|
|
955
|
+
// 基础错误处理
|
|
956
|
+
try {
|
|
957
|
+
const response = await apiClient.action('get_user', { user_id: 123 })
|
|
958
|
+
console.log('获取成功:', response.result)
|
|
959
|
+
} catch (error: any) {
|
|
960
|
+
if (error.status === 'error') {
|
|
961
|
+
console.error('错误代码:', error.code)
|
|
962
|
+
console.error('错误类型:', error.error_tpye)
|
|
963
|
+
console.error('错误消息:', error.message) // 已国际化的错误消息
|
|
964
|
+
console.error('时间戳:', error.timestamp)
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// 根据错误代码进行不同处理
|
|
969
|
+
try {
|
|
970
|
+
const response = await apiClient.action('sensitive_operation', data)
|
|
971
|
+
console.log('操作成功:', response.result)
|
|
972
|
+
} catch (error: any) {
|
|
973
|
+
if (error.status === 'error') {
|
|
974
|
+
switch (error.code) {
|
|
975
|
+
case 'UNAUTHORIZED':
|
|
976
|
+
// 401 未授权:跳转到登录页
|
|
977
|
+
router.push('/login')
|
|
978
|
+
break
|
|
979
|
+
case 'FORBIDDEN':
|
|
980
|
+
// 403 禁止访问:显示权限不足提示
|
|
981
|
+
showPermissionDeniedDialog()
|
|
982
|
+
break
|
|
983
|
+
case 'NOT_FOUND':
|
|
984
|
+
// 404 未找到:显示资源不存在提示
|
|
985
|
+
showNotFoundMessage()
|
|
986
|
+
break
|
|
987
|
+
case 'NETWORK_ERROR':
|
|
988
|
+
// 网络错误:提示检查网络连接
|
|
989
|
+
showNetworkErrorDialog()
|
|
990
|
+
break
|
|
991
|
+
case 'REQUEST_TIMEOUT':
|
|
992
|
+
// 请求超时:提示稍后重试
|
|
993
|
+
showTimeoutMessage()
|
|
994
|
+
break
|
|
995
|
+
default:
|
|
996
|
+
// 其他错误:显示通用错误提示
|
|
997
|
+
console.error('操作失败:', error.message)
|
|
998
|
+
break
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
```
|
|
1003
|
+
|
|
1004
|
+
**自动错误提示:**
|
|
1005
|
+
- UV-API 会自动使用 `@openuverse/rdesign` 的 `MessagePlugin` 显示错误提示
|
|
1006
|
+
- 错误消息会根据当前语言自动国际化(中文/英文)
|
|
1007
|
+
- 常见的 HTTP 错误(401、403、404、500 等)都有预定义的提示消息
|
|
1008
|
+
|
|
1009
|
+
##### 控制错误提示
|
|
1010
|
+
|
|
1011
|
+
UV-API 支持通过 `metadata` 选项控制是否显示错误提示,适用于轮询、后台任务等场景。
|
|
1012
|
+
|
|
1013
|
+
**基本用法:**
|
|
1014
|
+
|
|
1015
|
+
```typescript
|
|
1016
|
+
// 抑制错误提示
|
|
1017
|
+
const response = await apiClient.post('/api/data', data, {
|
|
1018
|
+
metadata: { suppressError: true }
|
|
1019
|
+
})
|
|
1020
|
+
|
|
1021
|
+
// 也适用于 action 方法
|
|
1022
|
+
const response2 = await apiClient.action('some_action', data, {
|
|
1023
|
+
metadata: { suppressError: true }
|
|
1024
|
+
})
|
|
1025
|
+
```
|
|
1026
|
+
|
|
1027
|
+
**适用场景:**
|
|
1028
|
+
|
|
1029
|
+
```typescript
|
|
1030
|
+
// 1. 轮询场景:避免频繁弹出错误提示
|
|
1031
|
+
const pollStatus = async () => {
|
|
1032
|
+
try {
|
|
1033
|
+
const response = await apiClient.get('/api/status', {
|
|
1034
|
+
metadata: { suppressError: true }
|
|
1035
|
+
})
|
|
1036
|
+
return response.result
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
// 静默失败,继续下次轮询
|
|
1039
|
+
return null
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
setInterval(pollStatus, 5000)
|
|
1043
|
+
|
|
1044
|
+
// 2. 后台检查:不影响用户体验
|
|
1045
|
+
const checkPermission = async () => {
|
|
1046
|
+
try {
|
|
1047
|
+
await apiClient.get('/api/check-permission', {
|
|
1048
|
+
metadata: { suppressError: true }
|
|
1049
|
+
})
|
|
1050
|
+
return true
|
|
1051
|
+
} catch (error) {
|
|
1052
|
+
return false
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
// 3. 可选数据加载:失败不影响主流程
|
|
1057
|
+
const loadOptionalData = async () => {
|
|
1058
|
+
try {
|
|
1059
|
+
const response = await apiClient.get('/api/optional-data', {
|
|
1060
|
+
metadata: { suppressError: true }
|
|
1061
|
+
})
|
|
1062
|
+
return response.result
|
|
1063
|
+
} catch (error) {
|
|
1064
|
+
// 使用默认值
|
|
1065
|
+
return defaultData
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
```
|
|
1069
|
+
|
|
1070
|
+
**注意事项:**
|
|
1071
|
+
- 即使抑制了错误提示,错误信息仍会记录在控制台中,便于调试
|
|
1072
|
+
- 错误对象的结构保持不变,仍然是 `ErrorResponse` 格式
|
|
1073
|
+
- 建议在业务代码中手动处理抑制的错误
|
|
1074
|
+
|
|
1075
|
+
##### 移除拦截器
|
|
1076
|
+
|
|
1077
|
+
```typescript
|
|
1078
|
+
// 移除请求拦截器
|
|
1079
|
+
apiClient.removeRequestInterceptor()
|
|
1080
|
+
|
|
1081
|
+
// 移除响应拦截器
|
|
1082
|
+
apiClient.removeResponseInterceptor()
|
|
1083
|
+
```
|
|
1084
|
+
|
|
1085
|
+
##### 获取 Axios 实例
|
|
1086
|
+
|
|
1087
|
+
```typescript
|
|
1088
|
+
// 如果需要更底层的控制,可以获取原始的 Axios 实例
|
|
1089
|
+
const axiosInstance = apiClient.getAxiosInstance()
|
|
1090
|
+
|
|
1091
|
+
// 添加自定义拦截器
|
|
1092
|
+
axiosInstance.interceptors.request.use((config) => {
|
|
1093
|
+
// 自定义请求处理
|
|
1094
|
+
return config
|
|
1095
|
+
})
|
|
1096
|
+
```
|
|
1097
|
+
|
|
1098
|
+
#### 完整使用示例
|
|
1099
|
+
|
|
1100
|
+
```typescript
|
|
1101
|
+
import { RestAPIClient } from '@openuverse/uvapi'
|
|
1102
|
+
|
|
1103
|
+
// 1. 创建客户端实例
|
|
1104
|
+
const apiClient = new RestAPIClient({
|
|
1105
|
+
baseURL: 'https://api.example.com',
|
|
1106
|
+
timeout: 10000,
|
|
1107
|
+
apiVersion: 'v1',
|
|
1108
|
+
workerId: 'my-service',
|
|
1109
|
+
urlType: 'header',
|
|
1110
|
+
headers: {
|
|
1111
|
+
'X-App-ID': 'my-app'
|
|
1112
|
+
}
|
|
1113
|
+
})
|
|
1114
|
+
|
|
1115
|
+
// 2. 使用基础 HTTP 方法(不推荐,建议使用 action)
|
|
1116
|
+
async function basicHttpExample() {
|
|
1117
|
+
// GET 请求
|
|
1118
|
+
const response = await apiClient.get<User[]>('/api/users')
|
|
1119
|
+
const users = response.result
|
|
1120
|
+
|
|
1121
|
+
// POST 请求
|
|
1122
|
+
const response2 = await apiClient.post<User>('/api/users', {
|
|
1123
|
+
name: '张三',
|
|
1124
|
+
email: 'zhangsan@example.com'
|
|
1125
|
+
})
|
|
1126
|
+
const newUser = response2.result
|
|
1127
|
+
|
|
1128
|
+
// PUT 请求
|
|
1129
|
+
const response3 = await apiClient.put<User>(`/api/users/${newUser.id}`, {
|
|
1130
|
+
name: '张三(已更新)'
|
|
1131
|
+
})
|
|
1132
|
+
const updatedUser = response3.result
|
|
1133
|
+
|
|
1134
|
+
// DELETE 请求
|
|
1135
|
+
const response4 = await apiClient.delete(`/api/users/${newUser.id}`)
|
|
1136
|
+
console.log(response4.status) // 'success'
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
// 3. 使用业务 action 方法
|
|
1140
|
+
async function businessActionExample() {
|
|
1141
|
+
// 调用业务接口
|
|
1142
|
+
const response = await apiClient.action('process_order', {
|
|
1143
|
+
order_id: 12345,
|
|
1144
|
+
action: 'confirm'
|
|
1145
|
+
})
|
|
1146
|
+
const result = response.result // 获取实际数据
|
|
1147
|
+
console.log('操作结果:', result)
|
|
1148
|
+
|
|
1149
|
+
// 获取数据
|
|
1150
|
+
const response2 = await apiClient.action('get_dashboard_data', {
|
|
1151
|
+
date_range: '7d'
|
|
1152
|
+
})
|
|
1153
|
+
const data = response2.result
|
|
1154
|
+
console.log('仪表板数据:', data)
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
// 4. 使用属性管理方法(⚠️ 暂不开放)
|
|
1158
|
+
// ⚠️ 注意:以下属性相关方法暂时不开放在 UI 中使用
|
|
1159
|
+
async function attributeExample() {
|
|
1160
|
+
// 获取所有属性(暂不开放)
|
|
1161
|
+
// const allAttrs = await apiClient.getAttributes()
|
|
1162
|
+
// console.log('所有属性:', allAttrs)
|
|
1163
|
+
|
|
1164
|
+
// 获取单个属性(暂不开放)
|
|
1165
|
+
// const status = await apiClient.getAttribute('status')
|
|
1166
|
+
// console.log('当前状态:', status)
|
|
1167
|
+
|
|
1168
|
+
// 设置单个属性(暂不开放)
|
|
1169
|
+
// await apiClient.setAttribute('status', 'active')
|
|
1170
|
+
|
|
1171
|
+
// 批量设置属性(暂不开放)
|
|
1172
|
+
// await apiClient.setAttributes({
|
|
1173
|
+
// status: 'active',
|
|
1174
|
+
// version: '2.0.0',
|
|
1175
|
+
// lastUpdate: new Date().toISOString()
|
|
1176
|
+
// })
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
// 5. 错误处理示例
|
|
1180
|
+
async function errorHandlingExample() {
|
|
1181
|
+
try {
|
|
1182
|
+
const response = await apiClient.action('risky_operation', { id: 123 })
|
|
1183
|
+
console.log('操作成功:', response.result)
|
|
1184
|
+
} catch (error: any) {
|
|
1185
|
+
if (error.status === 'error') {
|
|
1186
|
+
// 业务错误或 HTTP 错误
|
|
1187
|
+
console.error('错误代码:', error.code)
|
|
1188
|
+
console.error('错误类型:', error.error_tpye)
|
|
1189
|
+
console.error('错误消息:', error.message)
|
|
1190
|
+
|
|
1191
|
+
// 根据错误代码处理
|
|
1192
|
+
switch (error.code) {
|
|
1193
|
+
case 'UNAUTHORIZED':
|
|
1194
|
+
// 跳转到登录页
|
|
1195
|
+
break
|
|
1196
|
+
case 'FORBIDDEN':
|
|
1197
|
+
// 显示权限不足提示
|
|
1198
|
+
break
|
|
1199
|
+
case 'NOT_FOUND':
|
|
1200
|
+
// 显示资源不存在提示
|
|
1201
|
+
break
|
|
1202
|
+
default:
|
|
1203
|
+
// 其他错误处理
|
|
1204
|
+
break
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
// 执行示例
|
|
1211
|
+
basicHttpExample()
|
|
1212
|
+
businessActionExample()
|
|
1213
|
+
// attributeExample() // 属性方法暂不开放
|
|
1214
|
+
errorHandlingExample()
|
|
1215
|
+
```
|
|
1216
|
+
|
|
1217
|
+
---
|
|
1218
|
+
|
|
1219
|
+
### WebSocketClient - WebSocket 连接管理
|
|
1220
|
+
|
|
1221
|
+
> 💡 **推荐使用 `useAttributeMonitor`**:对于属性监听和 Store 同步场景,推荐使用 `useAttributeMonitor` Hook,无需直接创建 WebSocketClient 实例。
|
|
1222
|
+
>
|
|
1223
|
+
> `WebSocketClient` 仅供高级用法或自定义场景使用。
|
|
1224
|
+
|
|
1225
|
+
WebSocket 客户端提供完整的 WebSocket 连接管理功能,支持自动重连、消息队列和 MessagePack 自动解码。
|
|
1226
|
+
|
|
1227
|
+
**主要特性:**
|
|
1228
|
+
- ✅ 自动 URL 构建(格式:`/{apiVersion}/workers/attributes/{appId}/monitor`)
|
|
1229
|
+
- ✅ 自动重连机制
|
|
1230
|
+
- ✅ MessagePack 和 JSON 消息自动解码
|
|
1231
|
+
- ✅ 消息队列管理(未连接时自动缓存)
|
|
1232
|
+
- ✅ 完整的事件监听能力
|
|
1233
|
+
- ✅ 响应式状态管理
|
|
1234
|
+
|
|
1235
|
+
**使用建议:**
|
|
1236
|
+
- ✅ **属性监听和 Store 同步**:使用 `useAttributeMonitor` Hook(推荐)
|
|
1237
|
+
- 🔧 **自定义 WebSocket 需求**:直接使用 `WebSocketClient`(高级用法)
|
|
1238
|
+
|
|
1239
|
+
#### 创建实例
|
|
1240
|
+
|
|
1241
|
+
```typescript
|
|
1242
|
+
import { WebSocketClient } from '@openuverse/uvapi'
|
|
1243
|
+
|
|
1244
|
+
// 创建 WebSocket 客户端,自动构建 URL
|
|
1245
|
+
const wsClient = new WebSocketClient('target-app-id', {
|
|
1246
|
+
baseURL: 'ws://localhost:9898', // 可选,未配置时自动使用当前 host + 9898 端口
|
|
1247
|
+
apiVersion: 'v1', // 可选,默认 'v1'
|
|
1248
|
+
reconnectInterval: 5000, // 可选,重连间隔(毫秒),默认 5000
|
|
1249
|
+
maxReconnectAttempts: 5 // 可选,最大重连次数,默认 5
|
|
1250
|
+
})
|
|
1251
|
+
|
|
1252
|
+
// 自动构建的 WebSocket URL:
|
|
1253
|
+
// ws://localhost:9898/v1/workers/attributes/target-app-id/monitor
|
|
1254
|
+
```
|
|
1255
|
+
|
|
1256
|
+
**URL 自动构建规则:**
|
|
1257
|
+
- 未配置 `baseURL` 时,自动使用 `{protocol}//{hostname}:9898`
|
|
1258
|
+
- 协议根据当前页面自动选择(HTTP → ws://,HTTPS → wss://)
|
|
1259
|
+
- 路径格式:`/{apiVersion}/workers/attributes/{appId}/monitor`
|
|
1260
|
+
|
|
1261
|
+
#### 连接管理
|
|
1262
|
+
|
|
1263
|
+
##### 1. connect - 连接到服务器
|
|
1264
|
+
|
|
1265
|
+
```typescript
|
|
1266
|
+
// 连接到 WebSocket 服务器
|
|
1267
|
+
await wsClient.connect()
|
|
1268
|
+
|
|
1269
|
+
// 或连接到新的 URL
|
|
1270
|
+
await wsClient.connect('ws://new-server.com/ws')
|
|
1271
|
+
```
|
|
1272
|
+
|
|
1273
|
+
**参数说明:**
|
|
1274
|
+
- `url` (string, 可选) - WebSocket 服务器地址,如果不提供则使用构造函数中的地址
|
|
1275
|
+
|
|
1276
|
+
**返回值:** `Promise<void>` - 连接成功时 resolve
|
|
1277
|
+
|
|
1278
|
+
##### 2. close - 关闭连接
|
|
1279
|
+
|
|
1280
|
+
```typescript
|
|
1281
|
+
wsClient.close()
|
|
1282
|
+
|
|
1283
|
+
// 或指定关闭代码和原因
|
|
1284
|
+
wsClient.close(1000, '正常关闭')
|
|
1285
|
+
```
|
|
1286
|
+
|
|
1287
|
+
**参数说明:**
|
|
1288
|
+
- `code` (number, 可选) - WebSocket 关闭代码
|
|
1289
|
+
- `reason` (string, 可选) - 关闭原因
|
|
1290
|
+
|
|
1291
|
+
##### 3. isConnected - 检查连接状态
|
|
1292
|
+
|
|
1293
|
+
```typescript
|
|
1294
|
+
if (wsClient.isConnected()) {
|
|
1295
|
+
console.log('WebSocket 已连接')
|
|
1296
|
+
}
|
|
1297
|
+
```
|
|
1298
|
+
|
|
1299
|
+
**返回值:** `boolean` - 是否已连接
|
|
1300
|
+
|
|
1301
|
+
#### 消息发送
|
|
1302
|
+
|
|
1303
|
+
##### send - 发送消息
|
|
1304
|
+
|
|
1305
|
+
```typescript
|
|
1306
|
+
// 发送字符串消息
|
|
1307
|
+
wsClient.send('Hello Server')
|
|
1308
|
+
|
|
1309
|
+
// 发送对象消息(自动转为 JSON)
|
|
1310
|
+
wsClient.send({
|
|
1311
|
+
type: 'command',
|
|
1312
|
+
data: { action: 'start' }
|
|
1313
|
+
})
|
|
1314
|
+
```
|
|
1315
|
+
|
|
1316
|
+
**参数说明:**
|
|
1317
|
+
- `message` (string | object, 必填) - 要发送的消息
|
|
1318
|
+
- 对象会自动转为 JSON 字符串发送
|
|
1319
|
+
|
|
1320
|
+
**消息接收:**
|
|
1321
|
+
- UV-API 会自动尝试解析收到的消息:
|
|
1322
|
+
1. 首先尝试 JSON 解析
|
|
1323
|
+
2. 如果失败,尝试 MessagePack 解码(支持 Blob、ArrayBuffer、Uint8Array)
|
|
1324
|
+
3. 如果都失败,使用原始数据
|
|
1325
|
+
- 解码后的数据通过 `message` 事件传递
|
|
1326
|
+
|
|
1327
|
+
#### 事件监听
|
|
1328
|
+
|
|
1329
|
+
##### on - 注册事件监听器
|
|
1330
|
+
|
|
1331
|
+
```typescript
|
|
1332
|
+
// 连接打开事件
|
|
1333
|
+
wsClient.on('open', (event) => {
|
|
1334
|
+
console.log('WebSocket 连接已打开')
|
|
1335
|
+
})
|
|
1336
|
+
|
|
1337
|
+
// 接收消息事件
|
|
1338
|
+
wsClient.on('message', ({ data, rawEvent }) => {
|
|
1339
|
+
console.log('收到消息:', data)
|
|
1340
|
+
})
|
|
1341
|
+
|
|
1342
|
+
// 连接关闭事件
|
|
1343
|
+
wsClient.on('close', (event) => {
|
|
1344
|
+
console.log('WebSocket 连接已关闭:', event.code)
|
|
1345
|
+
})
|
|
1346
|
+
|
|
1347
|
+
// 连接错误事件
|
|
1348
|
+
wsClient.on('error', (event) => {
|
|
1349
|
+
console.error('WebSocket 连接错误:', event)
|
|
1350
|
+
})
|
|
1351
|
+
|
|
1352
|
+
// 重连事件
|
|
1353
|
+
wsClient.on('reconnect', ({ attempt }) => {
|
|
1354
|
+
console.log(`正在进行第 ${attempt} 次重连`)
|
|
1355
|
+
})
|
|
1356
|
+
|
|
1357
|
+
// 重连失败事件
|
|
1358
|
+
wsClient.on('reconnectFailed', ({ attempts }) => {
|
|
1359
|
+
console.error(`重连失败,已尝试 ${attempts} 次`)
|
|
1360
|
+
})
|
|
1361
|
+
```
|
|
1362
|
+
|
|
1363
|
+
**支持的事件类型:**
|
|
1364
|
+
- `open` - 连接打开
|
|
1365
|
+
- `close` - 连接关闭
|
|
1366
|
+
- `error` - 连接错误
|
|
1367
|
+
- `message` - 收到消息
|
|
1368
|
+
- `reconnect` - 正在重连
|
|
1369
|
+
- `reconnectFailed` - 重连失败
|
|
1370
|
+
|
|
1371
|
+
##### off - 移除事件监听器
|
|
1372
|
+
|
|
1373
|
+
```typescript
|
|
1374
|
+
const messageHandler = ({ data }) => {
|
|
1375
|
+
console.log('收到消息:', data)
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
// 注册监听器
|
|
1379
|
+
wsClient.on('message', messageHandler)
|
|
1380
|
+
|
|
1381
|
+
// 移除监听器
|
|
1382
|
+
wsClient.off('message', messageHandler)
|
|
1383
|
+
```
|
|
1384
|
+
|
|
1385
|
+
##### once - 注册一次性事件监听器
|
|
1386
|
+
|
|
1387
|
+
```typescript
|
|
1388
|
+
wsClient.once('open', () => {
|
|
1389
|
+
console.log('首次连接成功')
|
|
1390
|
+
})
|
|
1391
|
+
```
|
|
1392
|
+
|
|
1393
|
+
##### removeAllListeners - 移除所有监听器
|
|
1394
|
+
|
|
1395
|
+
```typescript
|
|
1396
|
+
// 移除特定事件的所有监听器
|
|
1397
|
+
wsClient.removeAllListeners('message')
|
|
1398
|
+
|
|
1399
|
+
// 移除所有事件的所有监听器
|
|
1400
|
+
wsClient.removeAllListeners()
|
|
1401
|
+
```
|
|
1402
|
+
|
|
1403
|
+
#### 工具方法
|
|
1404
|
+
|
|
1405
|
+
##### getReadyState - 获取连接状态
|
|
1406
|
+
|
|
1407
|
+
```typescript
|
|
1408
|
+
import { WebSocketState } from '@openuverse/uvapi'
|
|
1409
|
+
|
|
1410
|
+
const state = wsClient.getReadyState()
|
|
1411
|
+
|
|
1412
|
+
switch (state) {
|
|
1413
|
+
case WebSocketState.CONNECTING:
|
|
1414
|
+
console.log('正在连接')
|
|
1415
|
+
break
|
|
1416
|
+
case WebSocketState.OPEN:
|
|
1417
|
+
console.log('已连接')
|
|
1418
|
+
break
|
|
1419
|
+
case WebSocketState.CLOSING:
|
|
1420
|
+
console.log('正在关闭')
|
|
1421
|
+
break
|
|
1422
|
+
case WebSocketState.CLOSED:
|
|
1423
|
+
console.log('已关闭')
|
|
1424
|
+
break
|
|
1425
|
+
}
|
|
1426
|
+
```
|
|
1427
|
+
|
|
1428
|
+
**返回值:** `WebSocketState` - WebSocket 连接状态枚举值
|
|
1429
|
+
|
|
1430
|
+
##### getWebSocket - 获取原生 WebSocket 实例
|
|
1431
|
+
|
|
1432
|
+
```typescript
|
|
1433
|
+
const ws = wsClient.getWebSocket()
|
|
1434
|
+
if (ws) {
|
|
1435
|
+
console.log('原生 WebSocket 实例:', ws)
|
|
1436
|
+
}
|
|
1437
|
+
```
|
|
1438
|
+
|
|
1439
|
+
**返回值:** `WebSocket | null` - 原生 WebSocket 实例
|
|
1440
|
+
|
|
1441
|
+
##### getReconnectAttempts - 获取重连尝试次数
|
|
1442
|
+
|
|
1443
|
+
```typescript
|
|
1444
|
+
const attempts = wsClient.getReconnectAttempts()
|
|
1445
|
+
console.log(`已尝试重连 ${attempts} 次`)
|
|
1446
|
+
```
|
|
1447
|
+
|
|
1448
|
+
**返回值:** `number` - 重连尝试次数
|
|
1449
|
+
|
|
1450
|
+
##### getMessageQueueLength - 获取待发送消息队列长度
|
|
1451
|
+
|
|
1452
|
+
```typescript
|
|
1453
|
+
const queueLength = wsClient.getMessageQueueLength()
|
|
1454
|
+
console.log(`待发送消息数量: ${queueLength}`)
|
|
1455
|
+
```
|
|
1456
|
+
|
|
1457
|
+
**返回值:** `number` - 队列长度
|
|
1458
|
+
|
|
1459
|
+
##### clearMessageQueue - 清空消息队列
|
|
1460
|
+
|
|
1461
|
+
```typescript
|
|
1462
|
+
wsClient.clearMessageQueue()
|
|
1463
|
+
```
|
|
1464
|
+
|
|
1465
|
+
#### 完整使用示例
|
|
1466
|
+
|
|
1467
|
+
```typescript
|
|
1468
|
+
import { WebSocketClient, WebSocketState } from '@openuverse/uvapi'
|
|
1469
|
+
|
|
1470
|
+
// 创建 WebSocket 客户端
|
|
1471
|
+
const wsClient = new WebSocketClient('target-app-id', {
|
|
1472
|
+
reconnectInterval: 5000,
|
|
1473
|
+
maxReconnectAttempts: 5
|
|
1474
|
+
})
|
|
1475
|
+
|
|
1476
|
+
// 注册事件监听器
|
|
1477
|
+
wsClient.on('open', () => {
|
|
1478
|
+
console.log('连接成功')
|
|
1479
|
+
})
|
|
1480
|
+
|
|
1481
|
+
wsClient.on('message', ({ data, rawEvent }) => {
|
|
1482
|
+
console.log('收到消息:', data)
|
|
1483
|
+
|
|
1484
|
+
// 消息已自动解码(JSON 或 MessagePack)
|
|
1485
|
+
// 处理属性快照
|
|
1486
|
+
if (data.type === 'attribute_snapshot') {
|
|
1487
|
+
console.log('属性组:', data.group)
|
|
1488
|
+
console.log('收到属性快照:', data.attributes)
|
|
1489
|
+
console.log('时间戳:', data.timestamp)
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
// 处理属性变更
|
|
1493
|
+
if (data.type === 'attribute_change') {
|
|
1494
|
+
console.log('属性组:', data.group)
|
|
1495
|
+
console.log(`属性 ${data.attribute} 从 ${data.old_value} 变更为 ${data.value}`)
|
|
1496
|
+
console.log('时间戳:', data.timestamp)
|
|
1497
|
+
}
|
|
1498
|
+
})
|
|
1499
|
+
|
|
1500
|
+
wsClient.on('error', (error) => {
|
|
1501
|
+
console.error('连接错误:', error)
|
|
1502
|
+
})
|
|
1503
|
+
|
|
1504
|
+
wsClient.on('close', (event) => {
|
|
1505
|
+
console.log('连接关闭:', event.code, event.reason)
|
|
1506
|
+
})
|
|
1507
|
+
|
|
1508
|
+
wsClient.on('reconnect', ({ attempt }) => {
|
|
1509
|
+
console.log(`正在进行第 ${attempt} 次重连`)
|
|
1510
|
+
})
|
|
1511
|
+
|
|
1512
|
+
// 连接到服务器
|
|
1513
|
+
wsClient.connect().catch((error) => {
|
|
1514
|
+
console.error('连接失败:', error)
|
|
1515
|
+
})
|
|
1516
|
+
|
|
1517
|
+
// 断开连接(例如在组件卸载时)
|
|
1518
|
+
// wsClient.close()
|
|
1519
|
+
```
|
|
1520
|
+
|
|
1521
|
+
**重要说明:**
|
|
1522
|
+
- WebSocket 连接建立后,会自动接收后端推送的 `attribute_snapshot` 和 `attribute_change` 消息
|
|
1523
|
+
- 消息格式支持 JSON 和 MessagePack,UV-API 会自动解码
|
|
1524
|
+
- 消息包含以下关键字段:
|
|
1525
|
+
- `type`:消息类型('attribute_snapshot' 或 'attribute_change')
|
|
1526
|
+
- `group`:属性组名
|
|
1527
|
+
- `attributes` / `attribute` + `value`:属性数据
|
|
1528
|
+
- `old_value`:属性变更前的旧值(仅 CHANGE 消息)
|
|
1529
|
+
- `timestamp`:时间戳,用于时间戳比对,确保数据同步的准确性
|
|
1530
|
+
|
|
1531
|
+
---
|
|
1532
|
+
|
|
1533
|
+
## 🗄️ Store 状态管理
|
|
1534
|
+
|
|
1535
|
+
UV-API 提供了一个轻量级的响应式状态管理系统,类似 Pinia 的 API 设计,但更加轻量和灵活。支持:
|
|
1536
|
+
|
|
1537
|
+
- ✅ 响应式状态管理(基于 Vue3 reactive)
|
|
1538
|
+
- ✅ 时间戳管理(追踪数据更新时间)
|
|
1539
|
+
- ✅ 数据同步功能(自动从后端获取最新数据)
|
|
1540
|
+
- ✅ 状态订阅和监听
|
|
1541
|
+
- ✅ 深度合并和深拷贝
|
|
1542
|
+
- ✅ TypeScript 类型安全
|
|
1543
|
+
|
|
1544
|
+
> 💡 **推荐使用 `storeManager`**:建议使用 `storeManager.register()` 和 `storeManager.get()` 方法来创建和获取 Store,以实现统一管理。`createStore`、`defineStore` 和 `useStore` 仍可使用,但不推荐。
|
|
1545
|
+
|
|
1546
|
+
### createStore - 创建 Store(不建议使用)
|
|
1547
|
+
|
|
1548
|
+
> ⚠️ **不建议使用**:推荐使用 `storeManager.register()` 方法创建 Store,以便统一管理。
|
|
1549
|
+
|
|
1550
|
+
`createStore` 用于创建一个独立的响应式 Store 实例。此方法创建的 Store 不会自动注册到全局管理器中。
|
|
1551
|
+
|
|
1552
|
+
#### 基础用法
|
|
1553
|
+
|
|
1554
|
+
```typescript
|
|
1555
|
+
import { createStore } from '@openuverse/uvapi'
|
|
1556
|
+
|
|
1557
|
+
interface UserState {
|
|
1558
|
+
name: string
|
|
1559
|
+
age: number
|
|
1560
|
+
email: string
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
const userStore = createStore<UserState>({
|
|
1564
|
+
name: 'John',
|
|
1565
|
+
age: 25,
|
|
1566
|
+
email: 'john@example.com'
|
|
1567
|
+
})
|
|
1568
|
+
|
|
1569
|
+
// 直接访问和修改状态
|
|
1570
|
+
console.log(userStore.state.name) // 'John'
|
|
1571
|
+
userStore.state.name = 'Jane' // 响应式更新
|
|
1572
|
+
|
|
1573
|
+
// 使用 setState 更新(支持深度合并)
|
|
1574
|
+
userStore.setState({ name: 'Alice' })
|
|
1575
|
+
|
|
1576
|
+
// 使用函数方式更新(基于当前状态)
|
|
1577
|
+
userStore.setState(state => ({ age: state.age + 1 }))
|
|
1578
|
+
|
|
1579
|
+
// 批量更新
|
|
1580
|
+
userStore.batchUpdate(state => {
|
|
1581
|
+
state.name = 'Tom'
|
|
1582
|
+
state.age = 30
|
|
1583
|
+
state.email = 'tom@example.com'
|
|
1584
|
+
})
|
|
1585
|
+
|
|
1586
|
+
// 重置到初始状态
|
|
1587
|
+
userStore.reset()
|
|
1588
|
+
```
|
|
1589
|
+
|
|
1590
|
+
#### Store 配置选项
|
|
1591
|
+
|
|
1592
|
+
```typescript
|
|
1593
|
+
interface StoreOptions<T> {
|
|
1594
|
+
/** 状态变化时的回调函数 */
|
|
1595
|
+
onChange?: (newState: T, oldState: T) => void
|
|
1596
|
+
|
|
1597
|
+
/** 是否深度监听,默认 true */
|
|
1598
|
+
deep?: boolean
|
|
1599
|
+
|
|
1600
|
+
/**
|
|
1601
|
+
* 数据同步函数
|
|
1602
|
+
* 用于主动从后端或其他数据源获取最新数据
|
|
1603
|
+
* Store 注册时会自动调用一次
|
|
1604
|
+
*/
|
|
1605
|
+
syncData?: () => Promise<T>
|
|
1606
|
+
}
|
|
1607
|
+
|
|
1608
|
+
// 带配置的 Store
|
|
1609
|
+
const configStore = createStore({
|
|
1610
|
+
theme: 'light',
|
|
1611
|
+
language: 'zh-CN'
|
|
1612
|
+
}, {
|
|
1613
|
+
onChange: (newState, oldState) => {
|
|
1614
|
+
console.log('配置已更新:', { old: oldState, new: newState })
|
|
1615
|
+
},
|
|
1616
|
+
syncData: async () => {
|
|
1617
|
+
// 从后端获取最新配置
|
|
1618
|
+
const response = await apiClient.action('getConfig')
|
|
1619
|
+
return response.result
|
|
1620
|
+
}
|
|
1621
|
+
}, 'app-config') // 可选:传入 Store ID
|
|
1622
|
+
```
|
|
1623
|
+
|
|
1624
|
+
**Store 实例属性:**
|
|
1625
|
+
```typescript
|
|
1626
|
+
interface Store<T> {
|
|
1627
|
+
/** Store 的唯一标识符(通过 defineStore 或 register 创建时自动设置) */
|
|
1628
|
+
readonly id?: string
|
|
1629
|
+
|
|
1630
|
+
/** 属性组名称(从 id 中解析,用于后端 API 调用) */
|
|
1631
|
+
readonly attributeGroup?: string
|
|
1632
|
+
|
|
1633
|
+
/** 响应式状态对象 */
|
|
1634
|
+
readonly state: T
|
|
1635
|
+
|
|
1636
|
+
/** 响应式状态的解构引用 */
|
|
1637
|
+
readonly refs: ToRefs<T>
|
|
1638
|
+
|
|
1639
|
+
/** 其他方法... */
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
// 使用
|
|
1643
|
+
console.log(userStore.id) // 'user'
|
|
1644
|
+
console.log(userStore.attributeGroup) // 'user'
|
|
1645
|
+
```
|
|
1646
|
+
|
|
1647
|
+
**Store ID 格式约定:**
|
|
1648
|
+
|
|
1649
|
+
Store 的 `id` 支持两种格式,用于区分不同 worker 的同名属性组:
|
|
1650
|
+
|
|
1651
|
+
| id 格式 | 说明 | store.id | store.attributeGroup |
|
|
1652
|
+
|---------|------|----------|---------------------|
|
|
1653
|
+
| `worker1:DemoTaskAttributes` | 带 workerId 前缀 | `worker1:DemoTaskAttributes` | `DemoTaskAttributes` |
|
|
1654
|
+
| `user` | 不带前缀(向后兼容) | `user` | `user` |
|
|
1655
|
+
|
|
1656
|
+
```typescript
|
|
1657
|
+
// 示例:区分不同 worker 的 Store
|
|
1658
|
+
const store = storeManager.register(`${workerId}:DemoTaskAttributes`, initialState)
|
|
1659
|
+
console.log(store.id) // 'worker1:DemoTaskAttributes'
|
|
1660
|
+
console.log(store.attributeGroup) // 'DemoTaskAttributes'(用于 API 调用)
|
|
1661
|
+
```
|
|
1662
|
+
|
|
1663
|
+
#### Store 实例方法
|
|
1664
|
+
|
|
1665
|
+
##### 1. state - 响应式状态对象
|
|
1666
|
+
|
|
1667
|
+
```typescript
|
|
1668
|
+
// 直接读取
|
|
1669
|
+
console.log(store.state.name)
|
|
1670
|
+
|
|
1671
|
+
// 直接修改(会触发响应)
|
|
1672
|
+
store.state.name = 'New Name'
|
|
1673
|
+
|
|
1674
|
+
// 在模板中使用
|
|
1675
|
+
<input v-model="store.state.name" />
|
|
1676
|
+
```
|
|
1677
|
+
|
|
1678
|
+
##### 2. refs - 响应式引用
|
|
1679
|
+
|
|
1680
|
+
```typescript
|
|
1681
|
+
// 在 Composition API 中解构使用
|
|
1682
|
+
const { name, age } = store.refs
|
|
1683
|
+
|
|
1684
|
+
// 在模板中直接使用
|
|
1685
|
+
<div>{{ name }}</div>
|
|
1686
|
+
<div>{{ age }}</div>
|
|
1687
|
+
```
|
|
1688
|
+
|
|
1689
|
+
##### 3. getState() - 获取状态快照
|
|
1690
|
+
|
|
1691
|
+
```typescript
|
|
1692
|
+
const snapshot = store.getState()
|
|
1693
|
+
// 返回深拷贝,修改不影响原状态
|
|
1694
|
+
snapshot.name = 'Modified'
|
|
1695
|
+
```
|
|
1696
|
+
|
|
1697
|
+
##### 4. setState() - 更新部分状态
|
|
1698
|
+
|
|
1699
|
+
**方法签名:**
|
|
1700
|
+
```typescript
|
|
1701
|
+
setState(
|
|
1702
|
+
partial: DeepPartial<T> | ((state: T) => DeepPartial<T>),
|
|
1703
|
+
timestamp?: number
|
|
1704
|
+
): void
|
|
1705
|
+
```
|
|
1706
|
+
|
|
1707
|
+
**参数说明:**
|
|
1708
|
+
- `partial` - 部分状态对象或返回部分状态的函数
|
|
1709
|
+
- `timestamp` (可选) - 时间戳(毫秒),用于标记数据更新时间
|
|
1710
|
+
|
|
1711
|
+
**使用示例:**
|
|
1712
|
+
|
|
1713
|
+
```typescript
|
|
1714
|
+
// 对象方式:直接传入要更新的部分
|
|
1715
|
+
store.setState({ name: 'Alice' })
|
|
1716
|
+
|
|
1717
|
+
// 函数方式:基于当前状态计算
|
|
1718
|
+
store.setState(state => ({ age: state.age + 1 }))
|
|
1719
|
+
|
|
1720
|
+
// 深度合并(不会覆盖未指定的嵌套属性)
|
|
1721
|
+
store.setState({
|
|
1722
|
+
profile: {
|
|
1723
|
+
city: 'Beijing' // 只更新 city,保留其他 profile 属性
|
|
1724
|
+
}
|
|
1725
|
+
})
|
|
1726
|
+
|
|
1727
|
+
// 同时更新时间戳(重要!)
|
|
1728
|
+
store.setState({ name: 'Alice' }, Date.now())
|
|
1729
|
+
store.setState({ status: 'active' }, 1704067200000)
|
|
1730
|
+
|
|
1731
|
+
// WebSocket 消息同步时使用时间戳
|
|
1732
|
+
wsClient.on('message', (message) => {
|
|
1733
|
+
// 将后端数据和时间戳同步到 Store
|
|
1734
|
+
store.setState(message.attributes, new Date(message.timestamp).getTime())
|
|
1735
|
+
})
|
|
1736
|
+
```
|
|
1737
|
+
|
|
1738
|
+
**时间戳的作用:**
|
|
1739
|
+
- 🕐 **追踪更新时间**:记录数据最后更新的时间
|
|
1740
|
+
- 🔒 **防止过期覆盖**:通过 `getTimestamp()` 比对,避免旧数据覆盖新数据
|
|
1741
|
+
- 🔄 **数据同步**:在 WebSocket 属性监听中,确保数据同步的时序正确性
|
|
1742
|
+
- 📊 **调试追踪**:方便追踪数据来源和更新历史
|
|
1743
|
+
|
|
1744
|
+
**注意:**
|
|
1745
|
+
- 如果不传 `timestamp` 参数,Store 的时间戳不会更新
|
|
1746
|
+
- `useAttributeMonitor` 会自动传递后端消息的时间戳
|
|
1747
|
+
- 手动更新数据时,建议传入 `Date.now()` 更新时间戳
|
|
1748
|
+
|
|
1749
|
+
##### 5. batchUpdate() - 批量更新
|
|
1750
|
+
|
|
1751
|
+
```typescript
|
|
1752
|
+
// 批量修改多个属性
|
|
1753
|
+
store.batchUpdate(state => {
|
|
1754
|
+
state.name = 'Tom'
|
|
1755
|
+
state.age = 30
|
|
1756
|
+
state.email = 'tom@example.com'
|
|
1757
|
+
})
|
|
1758
|
+
```
|
|
1759
|
+
|
|
1760
|
+
##### 6. reset() - 重置到初始值
|
|
1761
|
+
|
|
1762
|
+
```typescript
|
|
1763
|
+
store.state.name = 'Modified'
|
|
1764
|
+
store.reset()
|
|
1765
|
+
console.log(store.state.name) // 恢复为初始值
|
|
1766
|
+
```
|
|
1767
|
+
|
|
1768
|
+
##### 7. subscribe() - 订阅状态变化
|
|
1769
|
+
|
|
1770
|
+
```typescript
|
|
1771
|
+
// 订阅状态变化
|
|
1772
|
+
const unsubscribe = store.subscribe((newState, oldState) => {
|
|
1773
|
+
console.log('状态变化:', { old: oldState.name, new: newState.name })
|
|
1774
|
+
})
|
|
1775
|
+
|
|
1776
|
+
// 取消订阅
|
|
1777
|
+
unsubscribe()
|
|
1778
|
+
```
|
|
1779
|
+
|
|
1780
|
+
##### 8. getTimestamp() / setTimestamp() - 时间戳管理
|
|
1781
|
+
|
|
1782
|
+
```typescript
|
|
1783
|
+
// 获取当前时间戳
|
|
1784
|
+
const timestamp = store.getTimestamp()
|
|
1785
|
+
console.log(timestamp) // 0 或最后更新的时间戳
|
|
1786
|
+
console.log(new Date(timestamp)) // 转换为 Date 对象
|
|
1787
|
+
|
|
1788
|
+
// 设置时间戳
|
|
1789
|
+
store.setTimestamp(Date.now())
|
|
1790
|
+
|
|
1791
|
+
// 在 setState 时同时更新时间戳
|
|
1792
|
+
store.setState({ name: 'Alice' }, Date.now())
|
|
1793
|
+
```
|
|
1794
|
+
|
|
1795
|
+
---
|
|
1796
|
+
|
|
1797
|
+
### defineStore - 定义并注册 Store(不建议使用)
|
|
1798
|
+
|
|
1799
|
+
> ⚠️ **不建议使用**:推荐使用 `storeManager.register()` 方法,提供更灵活的管理能力。
|
|
1800
|
+
|
|
1801
|
+
`defineStore` 会自动将 Store 注册到全局管理器中。
|
|
1802
|
+
|
|
1803
|
+
```typescript
|
|
1804
|
+
import { defineStore } from '@openuverse/uvapi'
|
|
1805
|
+
|
|
1806
|
+
// 定义用户 Store
|
|
1807
|
+
export const userStore = defineStore('user', {
|
|
1808
|
+
name: 'John',
|
|
1809
|
+
age: 25,
|
|
1810
|
+
email: 'john@example.com'
|
|
1811
|
+
}, {
|
|
1812
|
+
onChange: (newState, oldState) => {
|
|
1813
|
+
console.log('用户信息已更新')
|
|
1814
|
+
}
|
|
1815
|
+
})
|
|
1816
|
+
|
|
1817
|
+
// 在组件中使用
|
|
1818
|
+
console.log(userStore.state.name)
|
|
1819
|
+
userStore.setState({ name: 'Jane' })
|
|
1820
|
+
```
|
|
1821
|
+
|
|
1822
|
+
**带数据同步功能的 Store:**
|
|
1823
|
+
|
|
1824
|
+
```typescript
|
|
1825
|
+
// 定义配置 Store,自动从后端同步数据
|
|
1826
|
+
export const configStore = defineStore('config', {
|
|
1827
|
+
theme: 'light',
|
|
1828
|
+
language: 'zh-CN',
|
|
1829
|
+
autoSave: false
|
|
1830
|
+
}, {
|
|
1831
|
+
syncData: async () => {
|
|
1832
|
+
// Store 注册时会自动调用此函数获取初始数据
|
|
1833
|
+
const response = await apiClient.action('get_config')
|
|
1834
|
+
return response.result
|
|
1835
|
+
},
|
|
1836
|
+
onChange: (newState, oldState) => {
|
|
1837
|
+
// 监听配置变化,自动保存到后端
|
|
1838
|
+
if (newState.autoSave) {
|
|
1839
|
+
apiClient.action('save_config', newState)
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
})
|
|
1843
|
+
```
|
|
1844
|
+
|
|
1845
|
+
---
|
|
1846
|
+
|
|
1847
|
+
### useStore - 获取 Store 实例(不建议使用)
|
|
1848
|
+
|
|
1849
|
+
> ⚠️ **不建议使用**:推荐使用 `storeManager.get()` 方法获取 Store 实例。
|
|
1850
|
+
|
|
1851
|
+
`useStore` 用于在不同模块间共享已注册的 Store。
|
|
1852
|
+
|
|
1853
|
+
```typescript
|
|
1854
|
+
import { useStore } from '@openuverse/uvapi'
|
|
1855
|
+
|
|
1856
|
+
// 在组件或模块中获取 Store
|
|
1857
|
+
const userStore = useStore<UserState>('user')
|
|
1858
|
+
|
|
1859
|
+
if (userStore) {
|
|
1860
|
+
console.log(userStore.state.name)
|
|
1861
|
+
userStore.setState({ name: 'Alice' })
|
|
1862
|
+
} else {
|
|
1863
|
+
console.error('User store not found')
|
|
1864
|
+
}
|
|
1865
|
+
```
|
|
1866
|
+
|
|
1867
|
+
---
|
|
1868
|
+
|
|
1869
|
+
### storeManager - 全局 Store 管理器(推荐使用)
|
|
1870
|
+
|
|
1871
|
+
> ✅ **推荐使用**:storeManager 提供了完整的 Store 管理能力,是创建和管理 Store 的最佳方式。
|
|
1872
|
+
|
|
1873
|
+
全局单例 Store 管理器,用于统一管理所有 Store。
|
|
1874
|
+
|
|
1875
|
+
```typescript
|
|
1876
|
+
import { storeManager } from '@openuverse/uvapi'
|
|
1877
|
+
|
|
1878
|
+
// 注册 Store
|
|
1879
|
+
const userStore = storeManager.register('user', {
|
|
1880
|
+
name: 'John',
|
|
1881
|
+
age: 25
|
|
1882
|
+
}, {
|
|
1883
|
+
onChange: (newState, oldState) => {
|
|
1884
|
+
console.log('用户状态变化')
|
|
1885
|
+
}
|
|
1886
|
+
})
|
|
1887
|
+
|
|
1888
|
+
// 获取 Store
|
|
1889
|
+
const store = storeManager.get('user')
|
|
1890
|
+
|
|
1891
|
+
// 移除 Store
|
|
1892
|
+
storeManager.remove('user')
|
|
1893
|
+
|
|
1894
|
+
// 查看所有已注册的 Store
|
|
1895
|
+
console.log(storeManager.getAllIds()) // ['user', 'config', ...]
|
|
1896
|
+
|
|
1897
|
+
// 清空所有 Store
|
|
1898
|
+
storeManager.clear()
|
|
1899
|
+
```
|
|
1900
|
+
|
|
1901
|
+
---
|
|
1902
|
+
|
|
1903
|
+
### 完整使用示例(推荐方式:storeManager)
|
|
1904
|
+
|
|
1905
|
+
```typescript
|
|
1906
|
+
import { storeManager, RestAPIClient } from '@openuverse/uvapi'
|
|
1907
|
+
|
|
1908
|
+
// 创建 API 客户端
|
|
1909
|
+
const apiClient = new RestAPIClient()
|
|
1910
|
+
|
|
1911
|
+
// 定义应用配置 Store
|
|
1912
|
+
interface AppConfig {
|
|
1913
|
+
theme: 'light' | 'dark'
|
|
1914
|
+
language: string
|
|
1915
|
+
notifications: {
|
|
1916
|
+
email: boolean
|
|
1917
|
+
push: boolean
|
|
1918
|
+
}
|
|
1919
|
+
lastSyncTime: number
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
// 使用 storeManager 注册 Store(推荐方式)
|
|
1923
|
+
export const appConfigStore = storeManager.register<AppConfig>('app-config', {
|
|
1924
|
+
theme: 'light',
|
|
1925
|
+
language: 'zh-CN',
|
|
1926
|
+
notifications: {
|
|
1927
|
+
email: true,
|
|
1928
|
+
push: false
|
|
1929
|
+
},
|
|
1930
|
+
lastSyncTime: 0
|
|
1931
|
+
}, {
|
|
1932
|
+
// 从后端同步初始数据
|
|
1933
|
+
syncData: async () => {
|
|
1934
|
+
try {
|
|
1935
|
+
const response = await apiClient.action<AppConfig>('get_config')
|
|
1936
|
+
return response.result
|
|
1937
|
+
} catch (error) {
|
|
1938
|
+
console.error('同步配置失败:', error)
|
|
1939
|
+
throw error
|
|
1940
|
+
}
|
|
1941
|
+
},
|
|
1942
|
+
|
|
1943
|
+
// 监听配置变化
|
|
1944
|
+
onChange: async (newState, oldState) => {
|
|
1945
|
+
console.log('配置已更新:', { old: oldState, new: newState })
|
|
1946
|
+
|
|
1947
|
+
// 自动保存到后端
|
|
1948
|
+
try {
|
|
1949
|
+
await apiClient.action('save_config', newState)
|
|
1950
|
+
appConfigStore.setTimestamp(Date.now())
|
|
1951
|
+
} catch (error) {
|
|
1952
|
+
console.error('保存配置失败:', error)
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
})
|
|
1956
|
+
|
|
1957
|
+
// 在其他模块中获取已注册的 Store
|
|
1958
|
+
const configStore = storeManager.get<AppConfig>('app-config')
|
|
1959
|
+
if (configStore) {
|
|
1960
|
+
console.log(configStore.id) // 'app-config'
|
|
1961
|
+
console.log(configStore.state.theme) // 'light'
|
|
1962
|
+
}
|
|
1963
|
+
```
|
|
1964
|
+
|
|
1965
|
+
---
|
|
1966
|
+
|
|
1967
|
+
## ⚙️ 配置说明
|
|
1968
|
+
|
|
1969
|
+
### 配置项
|
|
1970
|
+
|
|
1971
|
+
#### PluginOptions - Vue 插件配置
|
|
1972
|
+
|
|
1973
|
+
```typescript
|
|
1974
|
+
interface PluginOptions {
|
|
1975
|
+
appId: string // 应用 ID(必需)
|
|
1976
|
+
restAPI?: RestAPIConfig // REST API 配置(可选)
|
|
1977
|
+
websocket?: WebSocketConfig // WebSocket 配置(可选)
|
|
1978
|
+
}
|
|
1979
|
+
```
|
|
1980
|
+
|
|
1981
|
+
#### RestAPIConfig - REST API 配置
|
|
1982
|
+
|
|
1983
|
+
```typescript
|
|
1984
|
+
interface RestAPIConfig {
|
|
1985
|
+
baseURL?: string // API 基础 URL
|
|
1986
|
+
timeout?: number // 请求超时时间(毫秒),默认 10000
|
|
1987
|
+
apiVersion?: string // API 版本号,默认 'v1'
|
|
1988
|
+
workerId?: string // Worker ID
|
|
1989
|
+
urlType?: 'path' | 'header' // URL 类型,默认 'header'
|
|
1990
|
+
headers?: Record<string, string> // 自定义请求头
|
|
1991
|
+
}
|
|
1992
|
+
```
|
|
1993
|
+
|
|
1994
|
+
#### WebSocketConfig - WebSocket 配置
|
|
1995
|
+
|
|
1996
|
+
```typescript
|
|
1997
|
+
interface WebSocketConfig {
|
|
1998
|
+
baseURL?: string // WebSocket 基础 URL,未配置时使用当前 host + 9898 端口
|
|
1999
|
+
apiVersion?: string // API 版本号,默认 'v1'
|
|
2000
|
+
reconnectInterval?: number // 重连间隔(毫秒),默认 5000
|
|
2001
|
+
maxReconnectAttempts?: number // 最大重连次数,默认 5
|
|
2002
|
+
}
|
|
2003
|
+
```
|
|
2004
|
+
|
|
2005
|
+
**注意:**
|
|
2006
|
+
- 如果未配置 `baseURL`,UV-API 会自动使用当前访问路径的 host + 9898 端口
|
|
2007
|
+
- 协议会根据当前页面自动选择(HTTP → ws://,HTTPS → wss://)
|
|
2008
|
+
- WebSocket URL 格式:`/{apiVersion}/workers/attributes/{appId}/monitor`
|
|
2009
|
+
|
|
2010
|
+
### 配置方式
|
|
2011
|
+
|
|
2012
|
+
#### 1. Vue 插件配置
|
|
2013
|
+
|
|
2014
|
+
**⚠️ 注意:使用插件前必须先注册 vue-i18n!**
|
|
2015
|
+
|
|
2016
|
+
```typescript
|
|
2017
|
+
import { setupI18n } from '@openuverse/uvapi'
|
|
2018
|
+
import RigolUVAPI from '@openuverse/uvapi'
|
|
2019
|
+
|
|
2020
|
+
// 1. 必须先初始化并注册国际化
|
|
2021
|
+
const i18n = setupI18n({
|
|
2022
|
+
locale: 'zh-CN',
|
|
2023
|
+
messages: {
|
|
2024
|
+
'zh-CN': { /* 您的中文翻译 */ },
|
|
2025
|
+
'en-US': { /* 您的英文翻译 */ }
|
|
2026
|
+
}
|
|
2027
|
+
})
|
|
2028
|
+
app.use(i18n)
|
|
2029
|
+
|
|
2030
|
+
// 2. 再注册 UV-API 插件
|
|
2031
|
+
app.use(RigolUVAPI, {
|
|
2032
|
+
appId: 'your-app-id',
|
|
2033
|
+
restAPI: {
|
|
2034
|
+
baseURL: 'https://api.example.com',
|
|
2035
|
+
timeout: 10000,
|
|
2036
|
+
urlType: 'header' // 或 'path'
|
|
2037
|
+
},
|
|
2038
|
+
websocket: {
|
|
2039
|
+
reconnectInterval: 5000,
|
|
2040
|
+
maxReconnectAttempts: 5
|
|
2041
|
+
}
|
|
2042
|
+
})
|
|
2043
|
+
```
|
|
2044
|
+
|
|
2045
|
+
#### 2. 客户端实例配置
|
|
2046
|
+
|
|
2047
|
+
```typescript
|
|
2048
|
+
import { UserClient } from '@openuverse/uvapi'
|
|
2049
|
+
|
|
2050
|
+
const userClient = new UserClient({
|
|
2051
|
+
baseURL: 'https://api.example.com',
|
|
2052
|
+
timeout: 10000,
|
|
2053
|
+
headers: {
|
|
2054
|
+
'Authorization': 'Bearer your-token',
|
|
2055
|
+
'X-Custom-Header': 'custom-value'
|
|
2056
|
+
}
|
|
2057
|
+
})
|
|
2058
|
+
```
|
|
2059
|
+
|
|
2060
|
+
#### 3. 多环境配置
|
|
2061
|
+
|
|
2062
|
+
```typescript
|
|
2063
|
+
// 开发环境
|
|
2064
|
+
const devClient = new UserClient({
|
|
2065
|
+
baseURL: 'https://api-dev.example.com',
|
|
2066
|
+
timeout: 30000
|
|
2067
|
+
})
|
|
2068
|
+
|
|
2069
|
+
// 生产环境
|
|
2070
|
+
const prodClient = new UserClient({
|
|
2071
|
+
baseURL: 'https://api-prod.example.com',
|
|
2072
|
+
timeout: 10000
|
|
2073
|
+
})
|
|
2074
|
+
```
|
|
2075
|
+
|
|
2076
|
+
---
|
|
2077
|
+
|
|
2078
|
+
## 🎣 Hooks
|
|
2079
|
+
|
|
2080
|
+
UV-API 提供了常用的 Vue Composition API Hooks,简化业务开发。
|
|
2081
|
+
|
|
2082
|
+
> ⚠️ **v0.1.8 变更**:`useLogin` Hook 已从本版本起移除,用户认证逻辑请在业务层自行实现。
|
|
2083
|
+
|
|
2084
|
+
### useAttributeMonitor - WebSocket 属性监听(推荐使用)
|
|
2085
|
+
|
|
2086
|
+
> ✅ **推荐使用**:这是实现属性监听和 Store 同步的最佳方式,无需手动创建 WebSocketClient 实例。
|
|
2087
|
+
|
|
2088
|
+
`useAttributeMonitor` 是一个强大的 Vue3 Composition API Hook,用于在组件中管理 WebSocket 连接,并自动同步后端属性变化到 Store。
|
|
2089
|
+
|
|
2090
|
+
**为什么使用 Hook:**
|
|
2091
|
+
- 🚀 **零配置**:只需提供 `appId` 和 `store`,所有 WebSocket 细节自动处理
|
|
2092
|
+
- 🔄 **自动化**:连接、快照获取、数据同步、重连全部自动完成
|
|
2093
|
+
- 🎯 **开箱即用**:与 Vue 组件生命周期完美集成,无需手动管理资源
|
|
2094
|
+
- 💯 **类型安全**:完整的 TypeScript 支持和类型推导
|
|
2095
|
+
|
|
2096
|
+
#### 特性
|
|
2097
|
+
|
|
2098
|
+
- ✅ **自动连接管理**:与组件生命周期同步(挂载时连接,卸载时断开)
|
|
2099
|
+
- ✅ **自动触发快照**:连接成功后自动调用 `trig_attributes_snapshot` action 获取全量属性
|
|
2100
|
+
- ✅ **响应式状态**:isConnected、readyState、reconnectAttempts
|
|
2101
|
+
- ✅ **自动重连机制**:支持配置重连间隔和最大次数
|
|
2102
|
+
- ✅ **与 Store 集成**:自动将属性变化同步到 Store
|
|
2103
|
+
- ✅ **MessagePack 支持**:自动解码 MessagePack 和 JSON 消息
|
|
2104
|
+
- ✅ **时间戳比对**:避免过期数据覆盖新数据
|
|
2105
|
+
- ✅ **完整事件监听**:支持所有 WebSocket 生命周期事件
|
|
2106
|
+
- ✅ **零手动代码**:无需创建 WebSocketClient,无需手动请求快照,无需手动同步数据
|
|
2107
|
+
|
|
2108
|
+
#### 基础用法
|
|
2109
|
+
|
|
2110
|
+
**最简单的属性监听实现:**
|
|
2111
|
+
|
|
2112
|
+
```typescript
|
|
2113
|
+
import { storeManager, useAttributeMonitor } from '@openuverse/uvapi'
|
|
2114
|
+
|
|
2115
|
+
// 1. 创建 Store(在组件外部)
|
|
2116
|
+
const deviceStore = storeManager.register('device', {
|
|
2117
|
+
status: 'offline',
|
|
2118
|
+
temperature: 0,
|
|
2119
|
+
voltage: 0
|
|
2120
|
+
})
|
|
2121
|
+
|
|
2122
|
+
// 2. 在 Vue 组件中使用 Hook(就这么简单!)
|
|
2123
|
+
const { isConnected } = useAttributeMonitor({
|
|
2124
|
+
appId: 'device-app-id', // 目标应用 ID
|
|
2125
|
+
store: deviceStore // 关联 Store
|
|
2126
|
+
})
|
|
2127
|
+
|
|
2128
|
+
// 完成!属性会自动同步到 Store,无需其他代码
|
|
2129
|
+
// - 组件挂载时自动连接 WebSocket
|
|
2130
|
+
// - 连接成功后自动获取属性快照
|
|
2131
|
+
// - 属性变化自动同步到 Store
|
|
2132
|
+
// - 组件卸载时自动断开连接
|
|
2133
|
+
```
|
|
2134
|
+
|
|
2135
|
+
**关键优势:**
|
|
2136
|
+
- ✅ **无需创建 WebSocketClient**:Hook 内部自动创建和管理
|
|
2137
|
+
- ✅ **无需手动请求快照**:连接成功后自动触发
|
|
2138
|
+
- ✅ **无需手动同步数据**:收到消息自动更新 Store
|
|
2139
|
+
- ✅ **无需管理生命周期**:自动连接、自动断开
|
|
2140
|
+
- ✅ **无需处理重连**:自动重连机制
|
|
2141
|
+
|
|
2142
|
+
**自定义回调(可选):**
|
|
2143
|
+
|
|
2144
|
+
```typescript
|
|
2145
|
+
const { isConnected, send, close } = useAttributeMonitor({
|
|
2146
|
+
appId: 'target-app-id',
|
|
2147
|
+
store: deviceStore,
|
|
2148
|
+
|
|
2149
|
+
// 可选:监听连接事件
|
|
2150
|
+
onOpen: () => {
|
|
2151
|
+
console.log('连接成功')
|
|
2152
|
+
},
|
|
2153
|
+
|
|
2154
|
+
// 可选:自定义消息处理
|
|
2155
|
+
onMessage: (message) => {
|
|
2156
|
+
console.log('收到消息:', message)
|
|
2157
|
+
},
|
|
2158
|
+
|
|
2159
|
+
// 可选:监听连接关闭
|
|
2160
|
+
onClose: () => {
|
|
2161
|
+
console.log('连接关闭')
|
|
2162
|
+
}
|
|
2163
|
+
})
|
|
2164
|
+
|
|
2165
|
+
// 检查连接状态
|
|
2166
|
+
console.log(isConnected.value) // true 或 false
|
|
2167
|
+
|
|
2168
|
+
// 关闭连接(通常不需要,组件卸载时会自动关闭)
|
|
2169
|
+
// close()
|
|
2170
|
+
```
|
|
2171
|
+
|
|
2172
|
+
#### 配置选项
|
|
2173
|
+
|
|
2174
|
+
```typescript
|
|
2175
|
+
interface MonitorSocketConfig extends WebSocketConfig {
|
|
2176
|
+
/** 目标应用的 ID */
|
|
2177
|
+
appId?: string
|
|
2178
|
+
|
|
2179
|
+
/** 关联的 Store 实例,用于自动同步数据 */
|
|
2180
|
+
store?: Store<any>
|
|
2181
|
+
|
|
2182
|
+
/** 连接打开时的回调 */
|
|
2183
|
+
onOpen?: (event: any) => void
|
|
2184
|
+
|
|
2185
|
+
/** 收到消息时的回调 */
|
|
2186
|
+
onMessage?: (message: any) => void
|
|
2187
|
+
|
|
2188
|
+
/** 连接关闭时的回调 */
|
|
2189
|
+
onClose?: (event: any) => void
|
|
2190
|
+
|
|
2191
|
+
/** 连接错误时的回调 */
|
|
2192
|
+
onError?: (error: any) => void
|
|
2193
|
+
|
|
2194
|
+
/** 重连时的回调 */
|
|
2195
|
+
onReconnect?: (data: { attempt: number }) => void
|
|
2196
|
+
|
|
2197
|
+
/** 重连失败时的回调 */
|
|
2198
|
+
onReconnectFailed?: (data: { attempts: number }) => void
|
|
2199
|
+
|
|
2200
|
+
/** 是否自动连接,默认 true */
|
|
2201
|
+
autoConnect?: boolean
|
|
2202
|
+
|
|
2203
|
+
/** 重连间隔(毫秒),默认 5000 */
|
|
2204
|
+
reconnectInterval?: number
|
|
2205
|
+
|
|
2206
|
+
/** 最大重连次数,默认 5 */
|
|
2207
|
+
maxReconnectAttempts?: number
|
|
2208
|
+
}
|
|
2209
|
+
```
|
|
2210
|
+
|
|
2211
|
+
#### 与 Store 集成使用
|
|
2212
|
+
|
|
2213
|
+
**最强大的功能**:自动同步后端属性变化到 Store,并支持时间戳比对。
|
|
2214
|
+
|
|
2215
|
+
```typescript
|
|
2216
|
+
import { storeManager, useAttributeMonitor } from '@openuverse/uvapi'
|
|
2217
|
+
|
|
2218
|
+
// 定义 Store
|
|
2219
|
+
interface DeviceState {
|
|
2220
|
+
status: 'online' | 'offline' | 'error'
|
|
2221
|
+
temperature: number
|
|
2222
|
+
voltage: number
|
|
2223
|
+
current: number
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
// 使用 storeManager 注册 Store(推荐方式)
|
|
2227
|
+
const deviceStore = storeManager.register<DeviceState>('device', {
|
|
2228
|
+
status: 'offline',
|
|
2229
|
+
temperature: 0,
|
|
2230
|
+
voltage: 0,
|
|
2231
|
+
current: 0
|
|
2232
|
+
})
|
|
2233
|
+
|
|
2234
|
+
// 在组件中使用
|
|
2235
|
+
const {
|
|
2236
|
+
isConnected,
|
|
2237
|
+
readyState,
|
|
2238
|
+
reconnectAttempts,
|
|
2239
|
+
send,
|
|
2240
|
+
close
|
|
2241
|
+
} = useAttributeMonitor({
|
|
2242
|
+
appId: 'device-001',
|
|
2243
|
+
store: deviceStore, // 关联 Store,自动同步数据
|
|
2244
|
+
autoConnect: true,
|
|
2245
|
+
|
|
2246
|
+
onOpen: () => {
|
|
2247
|
+
console.log('设备监控连接成功')
|
|
2248
|
+
// Hook 会自动触发 trig_attributes_snapshot 获取全量属性
|
|
2249
|
+
// 后端会自动推送属性快照和变更消息
|
|
2250
|
+
},
|
|
2251
|
+
|
|
2252
|
+
onClose: () => {
|
|
2253
|
+
console.log('设备监控连接关闭')
|
|
2254
|
+
},
|
|
2255
|
+
|
|
2256
|
+
onReconnect: ({ attempt }) => {
|
|
2257
|
+
console.log(`正在进行第 ${attempt} 次重连`)
|
|
2258
|
+
}
|
|
2259
|
+
})
|
|
2260
|
+
```
|
|
2261
|
+
|
|
2262
|
+
**WebSocket 消息格式:**
|
|
2263
|
+
|
|
2264
|
+
UV-API 支持两种消息类型,会自动同步到 Store:
|
|
2265
|
+
|
|
2266
|
+
1. **SNAPSHOT(属性快照)**:完整的状态数据
|
|
2267
|
+
```typescript
|
|
2268
|
+
{
|
|
2269
|
+
type: 'attribute_snapshot', // WsMessageType.SNAPSHOT
|
|
2270
|
+
group: 'GroupNameA', // 属性组名
|
|
2271
|
+
attributes: {
|
|
2272
|
+
attr_name_a: 'value_a',
|
|
2273
|
+
attr_name_b: 'value_b',
|
|
2274
|
+
status: 'online',
|
|
2275
|
+
temperature: 25.5,
|
|
2276
|
+
voltage: 220,
|
|
2277
|
+
current: 1.5
|
|
2278
|
+
},
|
|
2279
|
+
timestamp: 1761559940777 // 时间戳
|
|
2280
|
+
}
|
|
2281
|
+
```
|
|
2282
|
+
|
|
2283
|
+
2. **CHANGE(属性变更)**:单个属性的变化
|
|
2284
|
+
```typescript
|
|
2285
|
+
{
|
|
2286
|
+
type: 'attribute_change', // WsMessageType.CHANGE
|
|
2287
|
+
group: 'GroupNameA', // 属性组名
|
|
2288
|
+
attribute: 'temperature', // 变更的属性名
|
|
2289
|
+
old_value: 25.5, // 此属性的旧值
|
|
2290
|
+
value: 26.0, // 新值
|
|
2291
|
+
timestamp: 1761559940777 // 时间戳
|
|
2292
|
+
}
|
|
2293
|
+
```
|
|
2294
|
+
|
|
2295
|
+
**消息字段说明:**
|
|
2296
|
+
|
|
2297
|
+
| 字段 | SNAPSHOT | CHANGE | 说明 |
|
|
2298
|
+
|------|----------|--------|------|
|
|
2299
|
+
| `type` | ✅ | ✅ | 消息类型:'attribute_snapshot' 或 'attribute_change' |
|
|
2300
|
+
| `group` | ✅ | ✅ | 属性组名,用于分组管理属性 |
|
|
2301
|
+
| `attributes` | ✅ | - | 完整的属性对象(仅 SNAPSHOT) |
|
|
2302
|
+
| `attribute` | - | ✅ | 变更的属性名(仅 CHANGE) |
|
|
2303
|
+
| `old_value` | - | ✅ | 属性的旧值(仅 CHANGE) |
|
|
2304
|
+
| `value` | - | ✅ | 属性的新值(仅 CHANGE) |
|
|
2305
|
+
| `timestamp` | ✅ | ✅ | 时间戳 |
|
|
2306
|
+
|
|
2307
|
+
**自动数据同步流程:**
|
|
2308
|
+
|
|
2309
|
+
1. **连接成功**:Hook 自动调用 `trig_attributes_snapshot` action,请求后端推送完整属性快照(使用 `store.attributeGroup` 作为 `group_name`)
|
|
2310
|
+
2. **消息过滤**:自动过滤 `message.group !== store.attributeGroup` 的消息,确保只处理属于当前 Store 的属性
|
|
2311
|
+
3. **收到 SNAPSHOT**:
|
|
2312
|
+
- 提取 `attributes` 对象中的所有属性
|
|
2313
|
+
- 完整替换 Store 的状态
|
|
2314
|
+
- 更新 Store 的时间戳为消息中的 `timestamp`
|
|
2315
|
+
4. **收到 CHANGE**:
|
|
2316
|
+
- 只更新 `attribute` 指定的单个属性为 `value`
|
|
2317
|
+
- 更新 Store 的时间戳为消息中的 `timestamp`
|
|
2318
|
+
5. **时间戳保护**:如果消息时间戳早于 Store 时间戳,自动忽略过期数据
|
|
2319
|
+
|
|
2320
|
+
```typescript
|
|
2321
|
+
// 时间戳比对逻辑(自动执行)
|
|
2322
|
+
if (new Date(message.timestamp).getTime() < store.getTimestamp()) {
|
|
2323
|
+
return // 忽略过期数据,避免覆盖新数据
|
|
2324
|
+
}
|
|
2325
|
+
```
|
|
2326
|
+
|
|
2327
|
+
**MessagePack 支持:**
|
|
2328
|
+
- WebSocket 客户端会自动检测并解码 MessagePack 格式的消息
|
|
2329
|
+
- 支持 Blob、ArrayBuffer、Uint8Array 三种数据类型
|
|
2330
|
+
- 解码失败时自动降级到 JSON 解析,再失败则使用原始数据
|
|
2331
|
+
|
|
2332
|
+
#### 完整使用示例
|
|
2333
|
+
|
|
2334
|
+
```vue
|
|
2335
|
+
<template>
|
|
2336
|
+
<div class="device-monitor">
|
|
2337
|
+
<!-- 连接状态 -->
|
|
2338
|
+
<div class="status">
|
|
2339
|
+
<span :class="isConnected ? 'online' : 'offline'">
|
|
2340
|
+
{{ isConnected ? '已连接' : '未连接' }}
|
|
2341
|
+
</span>
|
|
2342
|
+
<span v-if="reconnectAttempts > 0">
|
|
2343
|
+
重连次数: {{ reconnectAttempts }}
|
|
2344
|
+
</span>
|
|
2345
|
+
</div>
|
|
2346
|
+
|
|
2347
|
+
<!-- 设备状态(自动同步到 Store) -->
|
|
2348
|
+
<div class="device-info">
|
|
2349
|
+
<div>状态: {{ deviceStore.state.status }}</div>
|
|
2350
|
+
<div>温度: {{ deviceStore.state.temperature }}°C</div>
|
|
2351
|
+
<div>电压: {{ deviceStore.state.voltage }}V</div>
|
|
2352
|
+
<div>电流: {{ deviceStore.state.current }}A</div>
|
|
2353
|
+
<div>最后更新: {{ formatTime(deviceStore.getTimestamp()) }}</div>
|
|
2354
|
+
</div>
|
|
2355
|
+
|
|
2356
|
+
<!-- 控制按钮 -->
|
|
2357
|
+
<div class="controls">
|
|
2358
|
+
<button @click="manualConnect" :disabled="isConnected">
|
|
2359
|
+
手动连接
|
|
2360
|
+
</button>
|
|
2361
|
+
<button @click="manualClose" :disabled="!isConnected">
|
|
2362
|
+
断开连接
|
|
2363
|
+
</button>
|
|
2364
|
+
<button @click="sendCommand">
|
|
2365
|
+
发送命令
|
|
2366
|
+
</button>
|
|
2367
|
+
</div>
|
|
2368
|
+
</div>
|
|
2369
|
+
</template>
|
|
2370
|
+
|
|
2371
|
+
<script setup lang="ts">
|
|
2372
|
+
import { storeManager, useAttributeMonitor } from '@openuverse/uvapi'
|
|
2373
|
+
|
|
2374
|
+
// 定义设备 Store(推荐使用 storeManager)
|
|
2375
|
+
interface DeviceState {
|
|
2376
|
+
status: 'online' | 'offline' | 'error'
|
|
2377
|
+
temperature: number
|
|
2378
|
+
voltage: number
|
|
2379
|
+
current: number
|
|
2380
|
+
}
|
|
2381
|
+
|
|
2382
|
+
const deviceStore = storeManager.register<DeviceState>('device', {
|
|
2383
|
+
status: 'offline',
|
|
2384
|
+
temperature: 0,
|
|
2385
|
+
voltage: 0,
|
|
2386
|
+
current: 0
|
|
2387
|
+
})
|
|
2388
|
+
|
|
2389
|
+
// 使用 WebSocket 监听
|
|
2390
|
+
const {
|
|
2391
|
+
isConnected,
|
|
2392
|
+
readyState,
|
|
2393
|
+
reconnectAttempts,
|
|
2394
|
+
connect,
|
|
2395
|
+
send,
|
|
2396
|
+
close,
|
|
2397
|
+
getMessageQueueLength,
|
|
2398
|
+
clearMessageQueue
|
|
2399
|
+
} = useAttributeMonitor({
|
|
2400
|
+
appId: 'device-001',
|
|
2401
|
+
store: deviceStore, // 自动同步数据到 Store
|
|
2402
|
+
autoConnect: true,
|
|
2403
|
+
reconnectInterval: 5000, // 5秒重连间隔
|
|
2404
|
+
maxReconnectAttempts: 10 // 最多重连10次
|
|
2405
|
+
|
|
2406
|
+
onOpen: (event) => {
|
|
2407
|
+
console.log('WebSocket 连接成功')
|
|
2408
|
+
// Hook 会自动调用 trig_attributes_snapshot action 获取全量属性快照
|
|
2409
|
+
// 无需手动请求,只需等待后端推送即可
|
|
2410
|
+
},
|
|
2411
|
+
|
|
2412
|
+
onMessage: (message) => {
|
|
2413
|
+
console.log('收到消息:', message)
|
|
2414
|
+
// 如果不关联 Store,可以在这里手动处理消息
|
|
2415
|
+
},
|
|
2416
|
+
|
|
2417
|
+
onClose: (event) => {
|
|
2418
|
+
console.log('WebSocket 连接关闭:', event.code, event.reason)
|
|
2419
|
+
},
|
|
2420
|
+
|
|
2421
|
+
onError: (error) => {
|
|
2422
|
+
console.error('WebSocket 错误:', error)
|
|
2423
|
+
},
|
|
2424
|
+
|
|
2425
|
+
onReconnect: ({ attempt }) => {
|
|
2426
|
+
console.log(`正在进行第 ${attempt} 次重连`)
|
|
2427
|
+
},
|
|
2428
|
+
|
|
2429
|
+
onReconnectFailed: ({ attempts }) => {
|
|
2430
|
+
console.error(`重连失败,已尝试 ${attempts} 次`)
|
|
2431
|
+
}
|
|
2432
|
+
})
|
|
2433
|
+
|
|
2434
|
+
// 格式化时间
|
|
2435
|
+
const formatTime = (timestamp: number) => {
|
|
2436
|
+
return timestamp ? new Date(timestamp).toLocaleString() : '从未更新'
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
// 手动连接
|
|
2440
|
+
const manualConnect = async () => {
|
|
2441
|
+
try {
|
|
2442
|
+
await connect()
|
|
2443
|
+
} catch (error) {
|
|
2444
|
+
console.error('连接失败:', error)
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
|
|
2448
|
+
// 手动关闭
|
|
2449
|
+
const manualClose = () => {
|
|
2450
|
+
close(1000, '用户主动断开')
|
|
2451
|
+
}
|
|
2452
|
+
|
|
2453
|
+
// 发送命令
|
|
2454
|
+
const sendCommand = () => {
|
|
2455
|
+
send({
|
|
2456
|
+
type: 'command',
|
|
2457
|
+
action: 'refresh',
|
|
2458
|
+
device: 'device-001'
|
|
2459
|
+
})
|
|
2460
|
+
}
|
|
2461
|
+
</script>
|
|
2462
|
+
|
|
2463
|
+
<style scoped>
|
|
2464
|
+
.online {
|
|
2465
|
+
color: green;
|
|
2466
|
+
}
|
|
2467
|
+
.offline {
|
|
2468
|
+
color: red;
|
|
2469
|
+
}
|
|
2470
|
+
</style>
|
|
2471
|
+
```
|
|
2472
|
+
|
|
2473
|
+
#### 返回值说明
|
|
2474
|
+
|
|
2475
|
+
`useAttributeMonitor` 返回一个对象,包含以下属性和方法:
|
|
2476
|
+
|
|
2477
|
+
**响应式状态:**
|
|
2478
|
+
- `isConnected: Ref<boolean>` - 是否已连接
|
|
2479
|
+
- `readyState: Ref<WebSocketState>` - 连接状态(CONNECTING、OPEN、CLOSING、CLOSED)
|
|
2480
|
+
- `reconnectAttempts: Ref<number>` - 重连尝试次数
|
|
2481
|
+
|
|
2482
|
+
**方法:**
|
|
2483
|
+
- `client: () => WebSocketClient | null` - 获取内部的 WebSocketClient 实例
|
|
2484
|
+
- `init: () => void` - 初始化 WebSocket 客户端(通常无需手动调用)
|
|
2485
|
+
- `connect: (url?: string) => Promise<void>` - 手动连接到服务器
|
|
2486
|
+
- `send: <T>(message: string | T) => void` - 发送消息
|
|
2487
|
+
- `close: (code?: number, reason?: string) => void` - 关闭连接
|
|
2488
|
+
- `cleanup: () => void` - 清理资源(通常无需手动调用)
|
|
2489
|
+
- `getMessageQueueLength: () => number` - 获取待发送消息队列长度
|
|
2490
|
+
- `clearMessageQueue: () => void` - 清空消息队列
|
|
2491
|
+
|
|
2492
|
+
**常用属性:**
|
|
2493
|
+
```typescript
|
|
2494
|
+
const {
|
|
2495
|
+
isConnected, // 响应式:连接状态
|
|
2496
|
+
readyState, // 响应式:WebSocket 状态
|
|
2497
|
+
reconnectAttempts, // 响应式:重连次数
|
|
2498
|
+
send, // 发送消息
|
|
2499
|
+
close, // 关闭连接
|
|
2500
|
+
connect // 手动连接
|
|
2501
|
+
} = useAttributeMonitor({ ... })
|
|
2502
|
+
```
|
|
2503
|
+
|
|
2504
|
+
#### 工作流程
|
|
2505
|
+
|
|
2506
|
+
1. **组件挂载**:Hook 自动创建 WebSocket 客户端并连接(如果 `autoConnect: true`)
|
|
2507
|
+
2. **连接成功**:Hook 自动调用 `trig_attributes_snapshot` action 请求全量属性快照
|
|
2508
|
+
3. **接收快照**:后端推送 `attribute_snapshot` 消息,Hook 自动更新 Store
|
|
2509
|
+
4. **接收变更**:后端推送 `attribute_change` 消息,Hook 自动更新 Store 中的对应属性
|
|
2510
|
+
5. **时间戳保护**:自动比对消息时间戳,忽略过期数据
|
|
2511
|
+
6. **组件卸载**:Hook 自动断开连接并清理资源
|
|
2512
|
+
|
|
2513
|
+
#### 最佳实践
|
|
2514
|
+
|
|
2515
|
+
1. **与 Store 集成**:推荐将 Store 传递给 Hook,实现自动数据同步
|
|
2516
|
+
2. **Store ID 格式**:使用 `${workerId}:${attributeGroup}` 格式区分不同 worker 的同名属性组
|
|
2517
|
+
3. **attributeGroup 使用**:Hook 会自动使用 `store.attributeGroup` 调用 API 和过滤消息
|
|
2518
|
+
4. **时间戳管理**:确保后端消息包含 `timestamp` 字段,Hook 会自动处理时间戳比对
|
|
2519
|
+
5. **消息格式**:后端推送的消息必须符合以下格式:
|
|
2520
|
+
- **SNAPSHOT**:包含 `type`、`group`、`attributes`、`timestamp` 字段
|
|
2521
|
+
- **CHANGE**:包含 `type`、`group`、`attribute`、`old_value`、`value`、`timestamp` 字段
|
|
2522
|
+
6. **属性组管理**:消息的 `group` 字段必须与 `store.attributeGroup` 匹配才会被处理
|
|
2523
|
+
7. **自动连接**:通常使用 `autoConnect: true`,让 Hook 管理连接生命周期
|
|
2524
|
+
8. **错误处理**:实现 `onError` 和 `onReconnectFailed` 回调处理异常情况
|
|
2525
|
+
9. **组件卸载**:Hook 会自动清理资源,无需手动处理
|
|
2526
|
+
|
|
2527
|
+
#### 后端消息格式要求
|
|
2528
|
+
|
|
2529
|
+
**attribute_snapshot 消息:**
|
|
2530
|
+
```typescript
|
|
2531
|
+
{
|
|
2532
|
+
type: 'attribute_snapshot', // 必需:消息类型
|
|
2533
|
+
group: string, // 必需:属性组名
|
|
2534
|
+
attributes: Record<string, any>, // 必需:完整的属性对象
|
|
2535
|
+
timestamp: number // 必需:时间戳(秒级或毫秒级浮点数)
|
|
2536
|
+
}
|
|
2537
|
+
```
|
|
2538
|
+
|
|
2539
|
+
**attribute_change 消息:**
|
|
2540
|
+
```typescript
|
|
2541
|
+
{
|
|
2542
|
+
type: 'attribute_change', // 必需:消息类型
|
|
2543
|
+
group: string, // 必需:属性组名
|
|
2544
|
+
attribute: string, // 必需:变更的属性名
|
|
2545
|
+
old_value: any, // 必需:属性的旧值
|
|
2546
|
+
value: any, // 必需:属性的新值
|
|
2547
|
+
timestamp: number // 必需:时间戳(秒级或毫秒级浮点数)
|
|
2548
|
+
}
|
|
2549
|
+
```
|
|
2550
|
+
|
|
2551
|
+
---
|
|
2552
|
+
|
|
2553
|
+
## 🌍 国际化
|
|
2554
|
+
|
|
2555
|
+
**⚠️ 重要:国际化是 UV-API 的必需功能!**
|
|
2556
|
+
|
|
2557
|
+
UV-API 提供了完整的国际化支持,基于 vue-i18n 实现,支持多语言切换和自定义语言包。UV-API 在处理错误时会使用国际化消息,因此必须正确配置 i18n。
|
|
2558
|
+
|
|
2559
|
+
### setupI18n - 初始化国际化(必需)
|
|
2560
|
+
|
|
2561
|
+
`setupI18n` 函数用于初始化 vue-i18n 实例,会自动合并 UV-API 内置的语言包。**这是使用 UV-API 的第一步,必须在注册 UV-API 插件之前完成。**
|
|
2562
|
+
|
|
2563
|
+
```typescript
|
|
2564
|
+
import { createApp } from 'vue'
|
|
2565
|
+
import { setupI18n } from '@openuverse/uvapi'
|
|
2566
|
+
import App from './App.vue'
|
|
2567
|
+
|
|
2568
|
+
const app = createApp(App)
|
|
2569
|
+
|
|
2570
|
+
// 初始化国际化
|
|
2571
|
+
const i18n = setupI18n({
|
|
2572
|
+
locale: 'zh-CN', // 默认语言
|
|
2573
|
+
messages: {
|
|
2574
|
+
'zh-CN': {
|
|
2575
|
+
app: {
|
|
2576
|
+
title: '我的应用',
|
|
2577
|
+
welcome: '欢迎使用'
|
|
2578
|
+
}
|
|
2579
|
+
},
|
|
2580
|
+
'en-US': {
|
|
2581
|
+
app: {
|
|
2582
|
+
title: 'My App',
|
|
2583
|
+
welcome: 'Welcome'
|
|
2584
|
+
}
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
})
|
|
2588
|
+
|
|
2589
|
+
app.use(i18n)
|
|
2590
|
+
app.mount('#app')
|
|
2591
|
+
```
|
|
2592
|
+
|
|
2593
|
+
**工作原理:**
|
|
2594
|
+
1. 从 `window.uVerseAPI.initialConfig.language` 获取 Electron 平台的语言设置(如果存在)
|
|
2595
|
+
2. 否则使用配置中的 `locale` 参数作为默认语言
|
|
2596
|
+
3. UV-API 会自动将内置的语言包(错误消息等)合并到您的语言包中
|
|
2597
|
+
4. 使用 `legacy: true` 模式创建 i18n 实例
|
|
2598
|
+
5. 自动注册 `registerLanguageChangeEvent` 监听器,当平台语言变化时自动同步
|
|
2599
|
+
|
|
2600
|
+
**重要说明:**
|
|
2601
|
+
- ⚠️ 不支持从 localStorage 读取或保存语言设置
|
|
2602
|
+
- ⚠️ 语言切换完全由 Electron 平台统一管理
|
|
2603
|
+
- ⚠️ 应用无法也不应该手动切换语言
|
|
2604
|
+
|
|
2605
|
+
### 内置语言包
|
|
2606
|
+
|
|
2607
|
+
UV-API 内置了常用的错误消息翻译:
|
|
2608
|
+
|
|
2609
|
+
**中文(zh-CN):**
|
|
2610
|
+
```typescript
|
|
2611
|
+
{
|
|
2612
|
+
uverse_uv_api: {
|
|
2613
|
+
unknown_error: '未知错误',
|
|
2614
|
+
request_timeout: '请求超时,请稍后重试',
|
|
2615
|
+
network_error: '网络连接失败,请检查网络',
|
|
2616
|
+
login_expired: '登录已过期,请重新登录',
|
|
2617
|
+
permission_denied: '权限不足,无法访问该资源',
|
|
2618
|
+
resource_not_found: '请求的资源不存在',
|
|
2619
|
+
// ... 更多消息
|
|
2620
|
+
}
|
|
2621
|
+
}
|
|
2622
|
+
```
|
|
2623
|
+
|
|
2624
|
+
**英文(en-US):**
|
|
2625
|
+
```typescript
|
|
2626
|
+
{
|
|
2627
|
+
uverse_uv_api: {
|
|
2628
|
+
unknown_error: 'Unknown error',
|
|
2629
|
+
request_timeout: 'Request timeout, please try again later',
|
|
2630
|
+
network_error: 'Network error, please check your network',
|
|
2631
|
+
login_expired: 'Login expired, please login again',
|
|
2632
|
+
permission_denied: 'Permission denied, cannot access this resource',
|
|
2633
|
+
resource_not_found: 'Resource not found',
|
|
2634
|
+
// ... 更多消息
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
```
|
|
2638
|
+
|
|
2639
|
+
### Electron 环境集成
|
|
2640
|
+
|
|
2641
|
+
**⚠️ 重要说明:**
|
|
2642
|
+
- 语言切换完全由 Electron 平台统一管理
|
|
2643
|
+
- UV-API 会自动通过平台 API 的 `registerLanguageChangeEvent` 监听并同步语言变化
|
|
2644
|
+
- 应用不需要也不应该手动切换语言
|
|
2645
|
+
|
|
2646
|
+
**平台 API:**
|
|
2647
|
+
|
|
2648
|
+
UV-API 提供了 `initMandatoryUVerseAPI` 函数简化 preload 脚本的编写:
|
|
2649
|
+
|
|
2650
|
+
```typescript
|
|
2651
|
+
// preload.ts
|
|
2652
|
+
import { contextBridge, ipcRenderer } from 'electron'
|
|
2653
|
+
import { initMandatoryUVerseAPI } from '@openuverse/uvapi/preload'
|
|
2654
|
+
|
|
2655
|
+
// 初始化并暴露 uVerseAPI
|
|
2656
|
+
const uVerseAPI = initMandatoryUVerseAPI(ipcRenderer)
|
|
2657
|
+
contextBridge.exposeInMainWorld('uVerseAPI', uVerseAPI)
|
|
2658
|
+
```
|
|
2659
|
+
|
|
2660
|
+
**主进程启动参数:**
|
|
2661
|
+
|
|
2662
|
+
```bash
|
|
2663
|
+
electron . \
|
|
2664
|
+
--initial-language=zh-CN \
|
|
2665
|
+
--initial-theme=dark \
|
|
2666
|
+
--view-type=ELECTRON_WEBCONTENTSVIEW \
|
|
2667
|
+
--server-hostname=localhost \
|
|
2668
|
+
--server-port=9898 \
|
|
2669
|
+
--server-protocol=http \
|
|
2670
|
+
--mcp-port=9899
|
|
2671
|
+
```
|
|
2672
|
+
|
|
2673
|
+
**baseURL 获取优先级:**
|
|
2674
|
+
1. 手动配置的 `baseURL`(最高优先级)
|
|
2675
|
+
2. `window.uVerseAPI.serverConfig`(Electron 环境)
|
|
2676
|
+
3. `window.location`(浏览器环境)
|
|
2677
|
+
4. 默认值 `http://localhost:9898` 或 `ws://localhost:9898`
|
|
2678
|
+
|
|
2679
|
+
### 浏览器模式初始化
|
|
2680
|
+
|
|
2681
|
+
当应用在纯浏览器环境(非 Electron)中运行时,UV-API 会自动进行浏览器模式初始化:
|
|
2682
|
+
|
|
2683
|
+
**功能特性:**
|
|
2684
|
+
- ✅ 自动连接 WebSocket 获取平台配置(主题、语言)
|
|
2685
|
+
- ✅ 延迟 `app.mount()` 直到获取初始配置
|
|
2686
|
+
- ✅ 自动同步主题和语言设置
|
|
2687
|
+
- ✅ 支持无限重连和重试机制
|
|
2688
|
+
|
|
2689
|
+
**工作流程:**
|
|
2690
|
+
1. 检测到没有 `window.uVerseAPI`,进入浏览器模式
|
|
2691
|
+
2. 重写 `app.mount()` 延迟实际挂载
|
|
2692
|
+
3. 连接 WebSocket 到 DaemonWorker 服务
|
|
2693
|
+
4. 获取 `platform_config` 属性快照
|
|
2694
|
+
5. 应用主题和语言设置
|
|
2695
|
+
6. 解除挂载阻塞,执行实际的 `app.mount()`
|
|
2696
|
+
|
|
2697
|
+
**配置 localStorage(可选):**
|
|
2698
|
+
```typescript
|
|
2699
|
+
// 自定义 WebSocket 服务器地址
|
|
2700
|
+
localStorage.setItem('_uverse-websocket-protocol', 'ws')
|
|
2701
|
+
localStorage.setItem('_uverse-websocket-hostname', 'localhost')
|
|
2702
|
+
localStorage.setItem('_uverse-websocket-port', '9898')
|
|
2703
|
+
```
|
|
2704
|
+
|
|
2705
|
+
**调试日志:**
|
|
2706
|
+
浏览器模式下会输出带 `[Browser Mode]` 前缀的调试日志,便于排查问题。
|
|
2707
|
+
|
|
2708
|
+
|
|
2709
|
+
### 完整使用示例
|
|
2710
|
+
|
|
2711
|
+
```typescript
|
|
2712
|
+
import { createApp } from 'vue'
|
|
2713
|
+
import RigolUVAPI, { setupI18n } from '@openuverse/uvapi'
|
|
2714
|
+
import App from './App.vue'
|
|
2715
|
+
|
|
2716
|
+
// 1. 初始化应用
|
|
2717
|
+
const app = createApp(App)
|
|
2718
|
+
|
|
2719
|
+
// 2. 设置国际化(必需,且必须在注册 UV-API 插件之前)
|
|
2720
|
+
const i18n = setupI18n({
|
|
2721
|
+
locale: 'zh-CN',
|
|
2722
|
+
messages: {
|
|
2723
|
+
'zh-CN': {
|
|
2724
|
+
common: {
|
|
2725
|
+
confirm: '确认',
|
|
2726
|
+
cancel: '取消'
|
|
2727
|
+
}
|
|
2728
|
+
},
|
|
2729
|
+
'en-US': {
|
|
2730
|
+
common: {
|
|
2731
|
+
confirm: 'Confirm',
|
|
2732
|
+
cancel: 'Cancel'
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
})
|
|
2737
|
+
|
|
2738
|
+
// 3. 注册 i18n 插件(必须在 UV-API 之前)
|
|
2739
|
+
app.use(i18n)
|
|
2740
|
+
|
|
2741
|
+
// 4. 注册 UV-API 插件(必须在 i18n 之后)
|
|
2742
|
+
app.use(RigolUVAPI, {
|
|
2743
|
+
appId: 'your-app-id',
|
|
2744
|
+
})
|
|
2745
|
+
|
|
2746
|
+
app.mount('#app')
|
|
2747
|
+
```
|
|
2748
|
+
|
|
2749
|
+
```vue
|
|
2750
|
+
<!-- 在 Vue 组件中使用 -->
|
|
2751
|
+
<template>
|
|
2752
|
+
<div>
|
|
2753
|
+
<h1>{{ $t('app.title') }}</h1>
|
|
2754
|
+
<p>{{ $t('uverse_uv_api.network_error') }}</p>
|
|
2755
|
+
</div>
|
|
2756
|
+
</template>
|
|
2757
|
+
|
|
2758
|
+
<script setup lang="ts">
|
|
2759
|
+
// 语言切换由 Electron 平台统一管理,会自动同步
|
|
2760
|
+
// 应用无需手动处理语言切换逻辑
|
|
2761
|
+
</script>
|
|
2762
|
+
```
|
|
2763
|
+
|
|
2764
|
+
---
|
|
2765
|
+
|
|
2766
|
+
## 🛠️ 工具函数
|
|
2767
|
+
|
|
2768
|
+
UV-API 提供了丰富的实用工具函数,涵盖存储管理和场景检测等功能。
|
|
2769
|
+
|
|
2770
|
+
### 存储管理工具
|
|
2771
|
+
|
|
2772
|
+
#### localStorage 工具函数
|
|
2773
|
+
|
|
2774
|
+
```typescript
|
|
2775
|
+
import {
|
|
2776
|
+
setLocalStorage,
|
|
2777
|
+
getLocalStorage,
|
|
2778
|
+
removeLocalStorage,
|
|
2779
|
+
clearLocalStorage
|
|
2780
|
+
} from '@openuverse/uvapi'
|
|
2781
|
+
|
|
2782
|
+
// 设置 localStorage 项
|
|
2783
|
+
setLocalStorage('user_name', 'zhangsan')
|
|
2784
|
+
|
|
2785
|
+
// 获取 localStorage 项
|
|
2786
|
+
const userName = getLocalStorage('user_name')
|
|
2787
|
+
console.log(userName) // 'zhangsan'
|
|
2788
|
+
|
|
2789
|
+
// 获取不存在的项,返回默认值
|
|
2790
|
+
const theme = getLocalStorage('theme', 'light')
|
|
2791
|
+
console.log(theme) // 'light'
|
|
2792
|
+
|
|
2793
|
+
// 删除 localStorage 项
|
|
2794
|
+
removeLocalStorage('user_name')
|
|
2795
|
+
|
|
2796
|
+
// 清空所有 localStorage
|
|
2797
|
+
clearLocalStorage()
|
|
2798
|
+
```
|
|
2799
|
+
|
|
2800
|
+
**函数签名:**
|
|
2801
|
+
- `setLocalStorage(key: string, value: string): void` - 设置项
|
|
2802
|
+
- `getLocalStorage(key: string, defaultValue?: string): string | null` - 获取项
|
|
2803
|
+
- `removeLocalStorage(key: string): void` - 删除项
|
|
2804
|
+
- `clearLocalStorage(): void` - 清空所有
|
|
2805
|
+
|
|
2806
|
+
#### sessionStorage 工具函数
|
|
2807
|
+
|
|
2808
|
+
```typescript
|
|
2809
|
+
import {
|
|
2810
|
+
setSessionStorage,
|
|
2811
|
+
getSessionStorage,
|
|
2812
|
+
removeSessionStorage,
|
|
2813
|
+
clearSessionStorage
|
|
2814
|
+
} from '@openuverse/uvapi'
|
|
2815
|
+
|
|
2816
|
+
// 设置 sessionStorage 项
|
|
2817
|
+
setSessionStorage('session_id', 'abc123')
|
|
2818
|
+
|
|
2819
|
+
// 获取 sessionStorage 项
|
|
2820
|
+
const sessionId = getSessionStorage('session_id')
|
|
2821
|
+
console.log(sessionId) // 'abc123'
|
|
2822
|
+
|
|
2823
|
+
// 获取不存在的项,返回默认值
|
|
2824
|
+
const tempData = getSessionStorage('temp_data', 'default')
|
|
2825
|
+
|
|
2826
|
+
// 删除 sessionStorage 项
|
|
2827
|
+
removeSessionStorage('session_id')
|
|
2828
|
+
|
|
2829
|
+
// 清空所有 sessionStorage
|
|
2830
|
+
clearSessionStorage()
|
|
2831
|
+
```
|
|
2832
|
+
|
|
2833
|
+
**函数签名:**
|
|
2834
|
+
- `setSessionStorage(key: string, value: string): void` - 设置项
|
|
2835
|
+
- `getSessionStorage(key: string, defaultValue?: string): string | null` - 获取项
|
|
2836
|
+
- `removeSessionStorage(key: string): void` - 删除项
|
|
2837
|
+
- `clearSessionStorage(): void` - 清空所有
|
|
2838
|
+
|
|
2839
|
+
**特性:**
|
|
2840
|
+
- 所有存储操作都有异常保护,失败时静默处理
|
|
2841
|
+
- 支持默认值,避免空值检查
|
|
2842
|
+
- TypeScript 类型安全
|
|
2843
|
+
|
|
2844
|
+
### 场景检测工具
|
|
2845
|
+
|
|
2846
|
+
UV-API 支持在不同环境中运行,提供了场景检测功能。
|
|
2847
|
+
|
|
2848
|
+
#### getCurrentScene - 获取当前运行场景
|
|
2849
|
+
|
|
2850
|
+
```typescript
|
|
2851
|
+
import { getCurrentScene, SceneType } from '@openuverse/uvapi'
|
|
2852
|
+
|
|
2853
|
+
const scene = getCurrentScene()
|
|
2854
|
+
|
|
2855
|
+
switch (scene) {
|
|
2856
|
+
case SceneType.STANDALONE:
|
|
2857
|
+
console.log('在浏览器中独立运行')
|
|
2858
|
+
break
|
|
2859
|
+
case SceneType.ELECTRON_BROWSERWINDOW:
|
|
2860
|
+
console.log('在 Electron BrowserWindow 中运行')
|
|
2861
|
+
break
|
|
2862
|
+
case SceneType.ELECTRON_WEBCONTENTSVIEW:
|
|
2863
|
+
console.log('在 Electron WebContentsView 中运行')
|
|
2864
|
+
break
|
|
2865
|
+
}
|
|
2866
|
+
```
|
|
2867
|
+
|
|
2868
|
+
**场景类型:**
|
|
2869
|
+
```typescript
|
|
2870
|
+
enum SceneType {
|
|
2871
|
+
/** 独立运行(在浏览器中直接打开) */
|
|
2872
|
+
STANDALONE = 'STANDALONE',
|
|
2873
|
+
|
|
2874
|
+
/** 在 Electron 环境中独立的 BrowserWindow 运行 */
|
|
2875
|
+
ELECTRON_BROWSERWINDOW = 'ELECTRON_BROWSERWINDOW',
|
|
2876
|
+
|
|
2877
|
+
/** 在 Electron 环境中 WebContentsView 运行 */
|
|
2878
|
+
ELECTRON_WEBCONTENTSVIEW = 'ELECTRON_WEBCONTENTSVIEW'
|
|
2879
|
+
}
|
|
2880
|
+
```
|
|
2881
|
+
|
|
2882
|
+
**使用场景:**
|
|
2883
|
+
```typescript
|
|
2884
|
+
import { getCurrentScene, SceneType } from '@openuverse/uvapi'
|
|
2885
|
+
|
|
2886
|
+
// 根据不同场景执行不同逻辑
|
|
2887
|
+
const scene = getCurrentScene()
|
|
2888
|
+
|
|
2889
|
+
if (scene === SceneType.STANDALONE) {
|
|
2890
|
+
// 浏览器环境:显示语言切换按钮
|
|
2891
|
+
showLanguageSelector()
|
|
2892
|
+
} else {
|
|
2893
|
+
// Electron 环境:隐藏语言切换按钮(由主进程统一管理)
|
|
2894
|
+
hideLanguageSelector()
|
|
2895
|
+
}
|
|
2896
|
+
```
|
|
2897
|
+
|
|
2898
|
+
### 常量定义
|
|
2899
|
+
|
|
2900
|
+
#### TOKEN_KEY、SceneType 和 WsMessageType
|
|
2901
|
+
|
|
2902
|
+
UV-API 定义的常量:
|
|
2903
|
+
|
|
2904
|
+
```typescript
|
|
2905
|
+
import { TOKEN_KEY, SceneType, WsMessageType } from '@openuverse/uvapi'
|
|
2906
|
+
|
|
2907
|
+
// localStorage 键名常量
|
|
2908
|
+
console.log(TOKEN_KEY) // 'rigol_token'
|
|
2909
|
+
|
|
2910
|
+
// 场景类型枚举
|
|
2911
|
+
console.log(SceneType.STANDALONE) // 'STANDALONE'
|
|
2912
|
+
console.log(SceneType.ELECTRON_BROWSERWINDOW) // 'ELECTRON_BROWSERWINDOW'
|
|
2913
|
+
console.log(SceneType.ELECTRON_WEBCONTENTSVIEW) // 'ELECTRON_WEBCONTENTSVIEW'
|
|
2914
|
+
|
|
2915
|
+
// WebSocket 消息类型常量
|
|
2916
|
+
console.log(WsMessageType.SNAPSHOT) // 'attribute_snapshot'
|
|
2917
|
+
console.log(WsMessageType.CHANGE) // 'attribute_change'
|
|
2918
|
+
|
|
2919
|
+
// 在业务代码中使用
|
|
2920
|
+
import { getLocalStorage, TOKEN_KEY } from '@openuverse/uvapi'
|
|
2921
|
+
|
|
2922
|
+
const tokenData = getLocalStorage(TOKEN_KEY)
|
|
2923
|
+
if (tokenData) {
|
|
2924
|
+
const { token, username } = JSON.parse(tokenData)
|
|
2925
|
+
console.log('当前用户:', username)
|
|
2926
|
+
}
|
|
2927
|
+
|
|
2928
|
+
// 在 WebSocket 消息处理中使用
|
|
2929
|
+
wsClient.on('message', ({ data }) => {
|
|
2930
|
+
if (data.type === WsMessageType.SNAPSHOT) {
|
|
2931
|
+
// 处理属性快照
|
|
2932
|
+
console.log('属性组:', data.group)
|
|
2933
|
+
console.log('收到完整属性:', data.attributes)
|
|
2934
|
+
console.log('时间戳:', data.timestamp)
|
|
2935
|
+
} else if (data.type === WsMessageType.CHANGE) {
|
|
2936
|
+
// 处理属性变更
|
|
2937
|
+
console.log('属性组:', data.group)
|
|
2938
|
+
console.log(`属性 ${data.attribute} 从 ${data.old_value} 变更为:`, data.value)
|
|
2939
|
+
console.log('时间戳:', data.timestamp)
|
|
2940
|
+
}
|
|
2941
|
+
})
|
|
2942
|
+
```
|
|
2943
|
+
|
|
2944
|
+
#### PLATFORM_INTERNAL_APPIDS - 平台应用 ID 常量
|
|
2945
|
+
|
|
2946
|
+
UV-API 提供了所有平台内置应用和服务的 ID 常量,这是一个**顶层导出的全局常量**,可以在任何项目中使用,方便应用间通信和服务调用。
|
|
2947
|
+
|
|
2948
|
+
```typescript
|
|
2949
|
+
import { PLATFORM_INTERNAL_APPIDS, PlatformAppId, getAppNameById } from '@openuverse/uvapi'
|
|
2950
|
+
|
|
2951
|
+
// 访问平台应用 ID
|
|
2952
|
+
console.log(PLATFORM_INTERNAL_APPIDS.UVAPP_INSTRUMENT_MANAGER) // 'd0a9a7f6473948c6b5ee204c4d4dea10'
|
|
2953
|
+
console.log(PLATFORM_INTERNAL_APPIDS.UVAPP_PACKAGE_MANAGER) // '14706eda67f34b7ebb4b487a0b6e7f2d'
|
|
2954
|
+
console.log(PLATFORM_INTERNAL_APPIDS.UVAPP_SRV_APIWORKER) // '2cfbbcdbbfcc41218be0700af688e5a8'
|
|
2955
|
+
|
|
2956
|
+
// 获取当前应用 ID(在 UV-API 初始化后自动设置)
|
|
2957
|
+
console.log(PLATFORM_INTERNAL_APPIDS.UVAPP_SELF)
|
|
2958
|
+
|
|
2959
|
+
// 使用类型检查
|
|
2960
|
+
const appId: PlatformAppId = 'd0a9a7f6473948c6b5ee204c4d4dea10' // ✅ 有效
|
|
2961
|
+
const invalidId: PlatformAppId = 'invalid-id' // ❌ TypeScript 编译错误
|
|
2962
|
+
|
|
2963
|
+
// 根据 ID 查找应用名称
|
|
2964
|
+
const appName = getAppNameById('d0a9a7f6473948c6b5ee204c4d4dea10')
|
|
2965
|
+
console.log(appName) // 'UVAPP_INSTRUMENT_MANAGER'
|
|
2966
|
+
|
|
2967
|
+
// 查找不存在的 ID
|
|
2968
|
+
const unknownName = getAppNameById('unknown-id')
|
|
2969
|
+
console.log(unknownName) // undefined
|
|
2970
|
+
```
|
|
2971
|
+
|
|
2972
|
+
**可用的平台应用 ID:**
|
|
2973
|
+
|
|
2974
|
+
| 常量名 | 说明 | ID 值 |
|
|
2975
|
+
|--------|------|-------|
|
|
2976
|
+
| `UVAPP_INSTRUMENT_MANAGER` | 仪器管理器应用 | `d0a9a7f6473948c6b5ee204c4d4dea10` |
|
|
2977
|
+
| `UVAPP_PACKAGE_MANAGER` | 包管理器应用 | `14706eda67f34b7ebb4b487a0b6e7f2d` |
|
|
2978
|
+
| `UVAPP_LOWCODE` | 低代码平台应用 | `c4f9b4ea0e4b4500b1176fe251510db8` |
|
|
2979
|
+
| `UVAPP_SRV_MESSAGEBUS` | 消息总线服务 | `e6c8dfd5d79045e8b3e21515aceda86d` |
|
|
2980
|
+
| `UVAPP_SRV_DAEMONWORKER` | 守护进程 Worker 服务 | `de34fa54b2c342b6b2afc496b819d285` |
|
|
2981
|
+
| `UVAPP_SRV_LOGGINGWORKER` | 日志 Worker 服务 | `35afa63c62524f25862d3f9fcc50d932` |
|
|
2982
|
+
| `UVAPP_SRV_APIWORKER` | API Worker 服务 | `2cfbbcdbbfcc41218be0700af688e5a8` |
|
|
2983
|
+
| `UVAPP_SRV_AIWORKER` | AI Worker 服务 | `d61cc09a1d8a48198ff5b6ab81dcbfd2` |
|
|
2984
|
+
| `UVAPP_SRV_STORAGEWORKER` | 存储 Worker 服务 | `f6f086417c484b0484d78e0bcbc5311a` |
|
|
2985
|
+
| `UVAPP_SRV_LICENSEWORKER` | 许可证 Worker 服务 | `48e5a3f7ffa14d5cb5a70485863dff1f` |
|
|
2986
|
+
| `UVAPP_SRV_SEQUENCEWORKER` | 序列 Worker 服务 | `01bfa07867bc4b09a323fce50b0cfd2b` |
|
|
2987
|
+
| `UVAPP_SELF` | 当前应用自身的 ID | *(UV-API 初始化时自动设置)* |
|
|
2988
|
+
|
|
2989
|
+
**特性:**
|
|
2990
|
+
- ✅ **只读保护**:使用 Proxy 防止外部修改,运行时拦截所有修改操作
|
|
2991
|
+
- ✅ **TypeScript 类型安全**:`Readonly<>` 类型保护,编译时阻止修改
|
|
2992
|
+
- ✅ **类型推导**:提供 `PlatformAppId` 类型用于严格的类型检查
|
|
2993
|
+
- ✅ **反向查找**:提供 `getAppNameById()` 工具函数,通过 ID 查找常量名
|
|
2994
|
+
|
|
2995
|
+
**使用场景:**
|
|
2996
|
+
```typescript
|
|
2997
|
+
import { PLATFORM_INTERNAL_APPIDS, RestAPIClient, WebSocketClient } from '@openuverse/uvapi'
|
|
2998
|
+
|
|
2999
|
+
// 1. 创建连接到特定服务的 API 客户端
|
|
3000
|
+
const apiClient = new RestAPIClient({
|
|
3001
|
+
baseURL: 'http://localhost:9898',
|
|
3002
|
+
workerId: PLATFORM_INTERNAL_APPIDS.UVAPP_SRV_APIWORKER
|
|
3003
|
+
})
|
|
3004
|
+
|
|
3005
|
+
// 2. 创建 WebSocket 连接监听特定应用
|
|
3006
|
+
const wsClient = new WebSocketClient(PLATFORM_INTERNAL_APPIDS.UVAPP_INSTRUMENT_MANAGER)
|
|
3007
|
+
|
|
3008
|
+
// 3. 在业务逻辑中判断应用类型
|
|
3009
|
+
if (currentAppId === PLATFORM_INTERNAL_APPIDS.UVAPP_LOWCODE) {
|
|
3010
|
+
// 低代码平台特有逻辑
|
|
3011
|
+
}
|
|
3012
|
+
|
|
3013
|
+
// 4. 应用间通信
|
|
3014
|
+
function sendMessageToApp(targetAppId: PlatformAppId, message: any) {
|
|
3015
|
+
// 发送消息到指定的平台应用
|
|
3016
|
+
messageBus.send(targetAppId, message)
|
|
3017
|
+
}
|
|
3018
|
+
|
|
3019
|
+
sendMessageToApp(PLATFORM_INTERNAL_APPIDS.UVAPP_SRV_MESSAGEBUS, {
|
|
3020
|
+
type: 'notification',
|
|
3021
|
+
content: 'Hello'
|
|
3022
|
+
})
|
|
3023
|
+
```
|
|
3024
|
+
|
|
3025
|
+
### 对象操作工具
|
|
3026
|
+
|
|
3027
|
+
#### deepClone - 深拷贝
|
|
3028
|
+
|
|
3029
|
+
```typescript
|
|
3030
|
+
import { deepClone } from '@openuverse/uvapi'
|
|
3031
|
+
|
|
3032
|
+
const original = {
|
|
3033
|
+
name: 'John',
|
|
3034
|
+
profile: {
|
|
3035
|
+
age: 25,
|
|
3036
|
+
address: {
|
|
3037
|
+
city: 'Beijing'
|
|
3038
|
+
}
|
|
3039
|
+
},
|
|
3040
|
+
hobbies: ['reading', 'coding']
|
|
3041
|
+
}
|
|
3042
|
+
|
|
3043
|
+
const cloned = deepClone(original)
|
|
3044
|
+
|
|
3045
|
+
// 修改克隆对象不影响原对象
|
|
3046
|
+
cloned.profile.age = 30
|
|
3047
|
+
cloned.profile.address.city = 'Shanghai'
|
|
3048
|
+
cloned.hobbies.push('gaming')
|
|
3049
|
+
|
|
3050
|
+
console.log(original.profile.age) // 25
|
|
3051
|
+
console.log(original.profile.address.city) // 'Beijing'
|
|
3052
|
+
console.log(original.hobbies.length) // 2
|
|
3053
|
+
```
|
|
3054
|
+
|
|
3055
|
+
**实现方式:** 使用 `JSON.parse(JSON.stringify(obj))`,简单高效,适合大多数场景。
|
|
3056
|
+
|
|
3057
|
+
**注意事项:**
|
|
3058
|
+
- 无法拷贝函数、Symbol、undefined
|
|
3059
|
+
- 无法拷贝循环引用的对象
|
|
3060
|
+
- Date 对象会被转为字符串
|
|
3061
|
+
- 对于简单数据结构完全够用
|
|
3062
|
+
|
|
3063
|
+
#### deepMerge - 深度合并
|
|
3064
|
+
|
|
3065
|
+
```typescript
|
|
3066
|
+
import { deepMerge } from '@openuverse/uvapi'
|
|
3067
|
+
|
|
3068
|
+
const target = {
|
|
3069
|
+
name: 'John',
|
|
3070
|
+
profile: {
|
|
3071
|
+
age: 25,
|
|
3072
|
+
address: {
|
|
3073
|
+
city: 'Beijing',
|
|
3074
|
+
country: 'China'
|
|
3075
|
+
}
|
|
3076
|
+
},
|
|
3077
|
+
hobbies: ['reading']
|
|
3078
|
+
}
|
|
3079
|
+
|
|
3080
|
+
const source = {
|
|
3081
|
+
profile: {
|
|
3082
|
+
age: 26, // 更新
|
|
3083
|
+
address: {
|
|
3084
|
+
city: 'Shanghai' // 更新,但保留 country
|
|
3085
|
+
},
|
|
3086
|
+
email: 'john@example.com' // 新增
|
|
3087
|
+
},
|
|
3088
|
+
hobbies: ['coding'] // 直接替换数组
|
|
3089
|
+
}
|
|
3090
|
+
|
|
3091
|
+
deepMerge(target, source)
|
|
3092
|
+
|
|
3093
|
+
console.log(target)
|
|
3094
|
+
// {
|
|
3095
|
+
// name: 'John', // 保留
|
|
3096
|
+
// profile: {
|
|
3097
|
+
// age: 26, // 已更新
|
|
3098
|
+
// address: {
|
|
3099
|
+
// city: 'Shanghai', // 已更新
|
|
3100
|
+
// country: 'China' // 保留
|
|
3101
|
+
// },
|
|
3102
|
+
// email: 'john@example.com' // 新增
|
|
3103
|
+
// },
|
|
3104
|
+
// hobbies: ['coding'] // 数组直接替换
|
|
3105
|
+
// }
|
|
3106
|
+
```
|
|
3107
|
+
|
|
3108
|
+
**特性:**
|
|
3109
|
+
- 递归合并嵌套对象
|
|
3110
|
+
- 数组和基本类型直接替换
|
|
3111
|
+
- 不会覆盖未指定的嵌套属性
|
|
3112
|
+
- 会修改目标对象(原地操作)
|
|
3113
|
+
|
|
3114
|
+
**使用场景:**
|
|
3115
|
+
- Store 状态更新(setState 方法内部使用)
|
|
3116
|
+
- 配置对象合并
|
|
3117
|
+
- 部分更新复杂对象
|
|
3118
|
+
|
|
3119
|
+
### MessagePack 工具
|
|
3120
|
+
|
|
3121
|
+
#### decodeMessagePack - 解码 MessagePack
|
|
3122
|
+
|
|
3123
|
+
> ℹ️ **自动处理**:WebSocketClient 和 useAttributeMonitor 会自动解码 MessagePack 消息,通常无需手动调用此函数。
|
|
3124
|
+
|
|
3125
|
+
`decodeMessagePack` 用于手动解码 MessagePack 格式的数据。
|
|
3126
|
+
|
|
3127
|
+
```typescript
|
|
3128
|
+
import { decodeMessagePack } from '@openuverse/uvapi'
|
|
3129
|
+
|
|
3130
|
+
// 手动解码 MessagePack 数据
|
|
3131
|
+
async function manualDecode(messagePackData: Blob | ArrayBuffer | Uint8Array) {
|
|
3132
|
+
try {
|
|
3133
|
+
const data = await decodeMessagePack(messagePackData)
|
|
3134
|
+
console.log('解码后的数据:', data)
|
|
3135
|
+
return data
|
|
3136
|
+
} catch (error) {
|
|
3137
|
+
console.error('解码失败:', error)
|
|
3138
|
+
throw error
|
|
3139
|
+
}
|
|
3140
|
+
}
|
|
3141
|
+
```
|
|
3142
|
+
|
|
3143
|
+
**支持的数据类型:**
|
|
3144
|
+
- `Blob` - 先转换为文本,然后解析为 JSON(用于文本格式的 Blob)
|
|
3145
|
+
- `ArrayBuffer` - 使用 MessagePack 解码器解码二进制数据
|
|
3146
|
+
- `Uint8Array` - 使用 MessagePack 解码器解码二进制数据
|
|
3147
|
+
|
|
3148
|
+
**自动解码:**
|
|
3149
|
+
- `WebSocketClient` 在接收消息时自动尝试解码:
|
|
3150
|
+
1. 首先尝试 JSON.parse
|
|
3151
|
+
2. 失败时尝试 MessagePack 解码
|
|
3152
|
+
3. 都失败时使用原始数据
|
|
3153
|
+
- `useAttributeMonitor` 继承了这个自动解码能力
|
|
3154
|
+
|
|
3155
|
+
**使用场景:**
|
|
3156
|
+
- 手动处理 MessagePack 数据
|
|
3157
|
+
- 自定义的 WebSocket 实现
|
|
3158
|
+
- 非 UV-API WebSocket 客户端的消息解码
|
|
3159
|
+
|
|
3160
|
+
### 📋 Logger - 日志工具
|
|
3161
|
+
|
|
3162
|
+
UV-API 提供了统一的日志工具 `logger`,支持日志级别过滤和主进程日志发送(Electron 环境)。
|
|
3163
|
+
|
|
3164
|
+
#### 基础用法
|
|
3165
|
+
|
|
3166
|
+
```typescript
|
|
3167
|
+
import { logger, LogLevel } from '@openuverse/uvapi'
|
|
3168
|
+
|
|
3169
|
+
// 输出不同级别的日志(仅 >= 当前级别的日志会被输出)
|
|
3170
|
+
logger.debug('调试信息')
|
|
3171
|
+
logger.info('运行信息')
|
|
3172
|
+
logger.warn('警告信息')
|
|
3173
|
+
logger.error('错误信息')
|
|
3174
|
+
```
|
|
3175
|
+
|
|
3176
|
+
#### 日志级别控制
|
|
3177
|
+
|
|
3178
|
+
`LogLevel` 枚举定义了以下级别(从低到高):
|
|
3179
|
+
|
|
3180
|
+
```typescript
|
|
3181
|
+
import { logger, LogLevel, setLogLevel } from '@openuverse/uvapi'
|
|
3182
|
+
|
|
3183
|
+
// 设置日志级别(低于此级别的日志将被过滤)
|
|
3184
|
+
setLogLevel(LogLevel.DEBUG) // 输出所有日志(开发模式推荐)
|
|
3185
|
+
setLogLevel(LogLevel.INFO) // 输出 INFO、WARN、ERROR(默认)
|
|
3186
|
+
setLogLevel(LogLevel.WARN) // 只输出 WARN 和 ERROR
|
|
3187
|
+
setLogLevel(LogLevel.ERROR) // 只输出 ERROR
|
|
3188
|
+
setLogLevel(LogLevel.OFF) // 关闭所有日志输出
|
|
3189
|
+
|
|
3190
|
+
// 也可以通过 logger 对象设置
|
|
3191
|
+
logger.setLevel(LogLevel.DEBUG)
|
|
3192
|
+
console.log(logger.getLevel()) // LogLevel.DEBUG
|
|
3193
|
+
```
|
|
3194
|
+
|
|
3195
|
+
#### 控制台输出开关
|
|
3196
|
+
|
|
3197
|
+
浏览器控制台输出**默认关闭**,避免日志污染用户环境。可按需启用:
|
|
3198
|
+
|
|
3199
|
+
```typescript
|
|
3200
|
+
import { logger } from '@openuverse/uvapi'
|
|
3201
|
+
|
|
3202
|
+
// 启用控制台输出(开发调试时使用)
|
|
3203
|
+
logger.setConsoleOutput(true)
|
|
3204
|
+
|
|
3205
|
+
// 关闭控制台输出(默认,生产环境)
|
|
3206
|
+
logger.setConsoleOutput(false)
|
|
3207
|
+
|
|
3208
|
+
console.log(logger.getConsoleOutput()) // false
|
|
3209
|
+
```
|
|
3210
|
+
|
|
3211
|
+
> ⚠️ **注意**:即使关闭控制台输出,日志仍会通过 `uVerseAPI.sendLog` 发送到主进程(Electron 环境)。
|
|
3212
|
+
|
|
3213
|
+
#### 日志来源标识
|
|
3214
|
+
|
|
3215
|
+
```typescript
|
|
3216
|
+
import { logger, setLogSource } from '@openuverse/uvapi'
|
|
3217
|
+
|
|
3218
|
+
// 设置日志来源(通常在应用初始化时由 UV-API 自动设置为 appId)
|
|
3219
|
+
setLogSource('my-app-id')
|
|
3220
|
+
console.log(logger.getSource()) // 'my-app-id'
|
|
3221
|
+
```
|
|
3222
|
+
|
|
3223
|
+
> 💡 **说明**:UV-API 会在插件安装(`app.use(RigolUVAPI, options)`)时自动将 `logSource` 设置为 `options.appId`,通常无需手动调用。
|
|
3224
|
+
|
|
3225
|
+
#### 完整 API 参考
|
|
3226
|
+
|
|
3227
|
+
| 方法 / 函数 | 说明 |
|
|
3228
|
+
|-------------|------|
|
|
3229
|
+
| `logger.debug(msg, ...args)` | 调试日志 |
|
|
3230
|
+
| `logger.info(msg, ...args)` | 信息日志 |
|
|
3231
|
+
| `logger.warn(msg, ...args)` | 警告日志 |
|
|
3232
|
+
| `logger.error(msg, ...args)` | 错误日志 |
|
|
3233
|
+
| `logger.setLevel(level)` | 设置日志级别 |
|
|
3234
|
+
| `logger.getLevel()` | 获取当前日志级别 |
|
|
3235
|
+
| `logger.setConsoleOutput(enabled)` | 设置控制台输出开关 |
|
|
3236
|
+
| `logger.getConsoleOutput()` | 获取控制台输出状态 |
|
|
3237
|
+
| `logger.setSource(source)` | 设置来源标识 |
|
|
3238
|
+
| `logger.getSource()` | 获取来源标识 |
|
|
3239
|
+
| `setLogLevel(level)` | 独立函数:设置日志级别 |
|
|
3240
|
+
| `getLogLevel()` | 独立函数:获取日志级别 |
|
|
3241
|
+
| `setLogSource(source)` | 独立函数:设置来源标识 |
|
|
3242
|
+
| `getLogSource()` | 独立函数:获取来源标识 |
|
|
3243
|
+
|
|
3244
|
+
---
|
|
3245
|
+
|
|
3246
|
+
### 完整工具函数示例
|
|
3247
|
+
|
|
3248
|
+
```typescript
|
|
3249
|
+
import {
|
|
3250
|
+
getCurrentScene,
|
|
3251
|
+
SceneType,
|
|
3252
|
+
setLocalStorage,
|
|
3253
|
+
getLocalStorage,
|
|
3254
|
+
TOKEN_KEY,
|
|
3255
|
+
WsMessageType,
|
|
3256
|
+
PLATFORM_INTERNAL_APPIDS,
|
|
3257
|
+
PlatformAppId,
|
|
3258
|
+
getAppNameById
|
|
3259
|
+
} from '@openuverse/uvapi'
|
|
3260
|
+
|
|
3261
|
+
// 用户登录后保存信息
|
|
3262
|
+
function saveUserInfo(userInfo: any) {
|
|
3263
|
+
setLocalStorage(TOKEN_KEY, JSON.stringify(userInfo))
|
|
3264
|
+
}
|
|
3265
|
+
|
|
3266
|
+
// 获取用户信息
|
|
3267
|
+
function getUserInfo() {
|
|
3268
|
+
const data = getLocalStorage(TOKEN_KEY)
|
|
3269
|
+
return data ? JSON.parse(data) : null
|
|
3270
|
+
}
|
|
3271
|
+
|
|
3272
|
+
// 保存用户偏好设置
|
|
3273
|
+
function saveUserPreferences(preferences: { theme: string; fontSize: number }) {
|
|
3274
|
+
setLocalStorage('user_preferences', JSON.stringify(preferences))
|
|
3275
|
+
}
|
|
3276
|
+
|
|
3277
|
+
// 获取用户偏好设置
|
|
3278
|
+
function getUserPreferences() {
|
|
3279
|
+
const data = getLocalStorage('user_preferences')
|
|
3280
|
+
return data ? JSON.parse(data) : { theme: 'light', fontSize: 14 }
|
|
3281
|
+
}
|
|
3282
|
+
|
|
3283
|
+
// 使用平台应用 ID 常量
|
|
3284
|
+
function connectToService(serviceId: PlatformAppId) {
|
|
3285
|
+
const serviceName = getAppNameById(serviceId)
|
|
3286
|
+
console.log(`正在连接到服务: ${serviceName}`)
|
|
3287
|
+
|
|
3288
|
+
// 创建到特定服务的连接
|
|
3289
|
+
const apiClient = new RestAPIClient({
|
|
3290
|
+
workerId: serviceId
|
|
3291
|
+
})
|
|
3292
|
+
|
|
3293
|
+
return apiClient
|
|
3294
|
+
}
|
|
3295
|
+
|
|
3296
|
+
// 示例:连接到 API Worker 服务
|
|
3297
|
+
const apiWorkerClient = connectToService(PLATFORM_INTERNAL_APPIDS.UVAPP_SRV_APIWORKER)
|
|
3298
|
+
```
|
|
3299
|
+
|
|
3300
|
+
---
|
|
3301
|
+
|
|
3302
|
+
## 🖥️ Electron Preload 功能
|
|
3303
|
+
|
|
3304
|
+
UV-API 提供了 Electron preload 脚本工具函数。
|
|
3305
|
+
|
|
3306
|
+
### getMainProcessArgs - 获取主进程参数
|
|
3307
|
+
|
|
3308
|
+
从主进程命令行参数中解析配置信息。
|
|
3309
|
+
|
|
3310
|
+
```typescript
|
|
3311
|
+
import { getMainProcessArgs, SceneType } from '@openuverse/uvapi/preload'
|
|
3312
|
+
|
|
3313
|
+
const args = getMainProcessArgs()
|
|
3314
|
+
|
|
3315
|
+
console.log(args.language) // 'zh-CN'
|
|
3316
|
+
console.log(args.theme) // 'dark'
|
|
3317
|
+
console.log(args.view_type) // SceneType.ELECTRON_WEBCONTENTSVIEW
|
|
3318
|
+
console.log(args.hostname) // 'localhost'
|
|
3319
|
+
console.log(args.port) // '9898'
|
|
3320
|
+
console.log(args.protocol) // 'http'
|
|
3321
|
+
console.log(args.mcp_port) // '9899'
|
|
3322
|
+
console.log(args.hide_guide) // false
|
|
3323
|
+
```
|
|
3324
|
+
|
|
3325
|
+
**支持的命令行参数:**
|
|
3326
|
+
|
|
3327
|
+
| 参数 | 类型 | 默认值 | 描述 |
|
|
3328
|
+
|------|------|--------|------|
|
|
3329
|
+
| `--initial-language` | string | `'zh-CN'` | 初始语言设置 |
|
|
3330
|
+
| `--initial-theme` | string | `'dark'` | 初始主题设置 |
|
|
3331
|
+
| `--view-type` | SceneType | `ELECTRON_WEBCONTENTSVIEW` | 视图类型 |
|
|
3332
|
+
| `--server-hostname` | string | `'localhost'` | 服务器主机名 |
|
|
3333
|
+
| `--server-port` | string | `'9898'` | 服务器端口 |
|
|
3334
|
+
| `--server-protocol` | string | `'http'` | 服务器协议 |
|
|
3335
|
+
| `--mcp-port` | string | `'9899'` | MCP 服务端口 |
|
|
3336
|
+
| `--hide-guide` | boolean | `false` | 是否隐藏引导页 |
|
|
3337
|
+
|
|
3338
|
+
### initMandatoryUVerseAPI - 初始化平台 API
|
|
3339
|
+
|
|
3340
|
+
在 Electron preload 脚本中初始化 `uVerseAPI` 对象。
|
|
3341
|
+
|
|
3342
|
+
```typescript
|
|
3343
|
+
import { contextBridge, ipcRenderer } from 'electron'
|
|
3344
|
+
import { initMandatoryUVerseAPI } from '@openuverse/uvapi/preload'
|
|
3345
|
+
|
|
3346
|
+
const uVerseAPI = initMandatoryUVerseAPI(ipcRenderer)
|
|
3347
|
+
contextBridge.exposeInMainWorld('uVerseAPI', uVerseAPI)
|
|
3348
|
+
```
|
|
3349
|
+
|
|
3350
|
+
**返回的 API 对象结构:**
|
|
3351
|
+
|
|
3352
|
+
```typescript
|
|
3353
|
+
{
|
|
3354
|
+
// 视图类型(从 --view-type 参数读取)
|
|
3355
|
+
viewType: 'STANDALONE' | 'ELECTRON_BROWSERWINDOW' | 'ELECTRON_WEBCONTENTSVIEW'
|
|
3356
|
+
|
|
3357
|
+
// 运行环境标识
|
|
3358
|
+
runningEnvironment: 'UVerse'
|
|
3359
|
+
|
|
3360
|
+
// 初始配置
|
|
3361
|
+
initialConfig: {
|
|
3362
|
+
language: string // 语言设置
|
|
3363
|
+
theme: string // 主题设置
|
|
3364
|
+
}
|
|
3365
|
+
|
|
3366
|
+
// 服务器配置
|
|
3367
|
+
serverConfig: {
|
|
3368
|
+
hostname: string
|
|
3369
|
+
port: string
|
|
3370
|
+
protocol: string
|
|
3371
|
+
mcp_port: string
|
|
3372
|
+
}
|
|
3373
|
+
|
|
3374
|
+
// 注册语言变更事件监听器
|
|
3375
|
+
registerLanguageChangeEvent: (callback: (language: string) => void) => () => void
|
|
3376
|
+
|
|
3377
|
+
// 注册主题变更事件监听器
|
|
3378
|
+
registerThemeChangeEvent: (callback: (theme: string) => void) => () => void
|
|
3379
|
+
}
|
|
3380
|
+
```
|
|
3381
|
+
|
|
3382
|
+
**完整的 Electron preload 脚本示例:**
|
|
3383
|
+
|
|
3384
|
+
```typescript
|
|
3385
|
+
// preload.ts
|
|
3386
|
+
import { contextBridge, ipcRenderer } from 'electron'
|
|
3387
|
+
import { initMandatoryUVerseAPI } from '@openuverse/uvapi/preload'
|
|
3388
|
+
|
|
3389
|
+
// 初始化 uVerseAPI
|
|
3390
|
+
const uVerseAPI = initMandatoryUVerseAPI(ipcRenderer)
|
|
3391
|
+
|
|
3392
|
+
// 暴露给渲染进程
|
|
3393
|
+
contextBridge.exposeInMainWorld('uVerseAPI', uVerseAPI)
|
|
3394
|
+
```
|
|
3395
|
+
|
|
3396
|
+
**在渲染进程中使用:**
|
|
3397
|
+
|
|
3398
|
+
```typescript
|
|
3399
|
+
// 访问配置
|
|
3400
|
+
const config = window.uVerseAPI.initialConfig
|
|
3401
|
+
console.log('当前语言:', config.language)
|
|
3402
|
+
console.log('当前主题:', config.theme)
|
|
3403
|
+
|
|
3404
|
+
// 访问服务器配置
|
|
3405
|
+
const server = window.uVerseAPI.serverConfig
|
|
3406
|
+
console.log('服务器地址:', `${server.protocol}://${server.hostname}:${server.port}`)
|
|
3407
|
+
|
|
3408
|
+
// 监听语言变化
|
|
3409
|
+
const unsubscribeLang = window.uVerseAPI.registerLanguageChangeEvent((newLanguage) => {
|
|
3410
|
+
console.log('语言已更改为:', newLanguage)
|
|
3411
|
+
})
|
|
3412
|
+
|
|
3413
|
+
// 监听主题变化
|
|
3414
|
+
const unsubscribeTheme = window.uVerseAPI.registerThemeChangeEvent((newTheme) => {
|
|
3415
|
+
console.log('主题已更改为:', newTheme)
|
|
3416
|
+
})
|
|
3417
|
+
|
|
3418
|
+
// 取消监听
|
|
3419
|
+
unsubscribeLang()
|
|
3420
|
+
unsubscribeTheme()
|
|
3421
|
+
```
|
|
3422
|
+
|
|
3423
|
+
**主进程启动参数示例:**
|
|
3424
|
+
|
|
3425
|
+
```bash
|
|
3426
|
+
# 启动 Electron 应用时传递参数
|
|
3427
|
+
electron . \
|
|
3428
|
+
--initial-language=zh-CN \
|
|
3429
|
+
--initial-theme=dark \
|
|
3430
|
+
--view-type=ELECTRON_WEBCONTENTSVIEW \
|
|
3431
|
+
--server-hostname=localhost \
|
|
3432
|
+
--server-port=9898 \
|
|
3433
|
+
--server-protocol=http \
|
|
3434
|
+
--mcp-port=9899
|
|
3435
|
+
```
|
|
3436
|
+
|
|
3437
|
+
---
|
|
3438
|
+
|
|
3439
|
+
## 📘 类型定义
|
|
3440
|
+
|
|
3441
|
+
UV-API 提供完整的 TypeScript 类型定义:
|
|
3442
|
+
|
|
3443
|
+
### API 响应类型
|
|
3444
|
+
|
|
3445
|
+
#### Response - 成功响应
|
|
3446
|
+
|
|
3447
|
+
```typescript
|
|
3448
|
+
interface Response<T> {
|
|
3449
|
+
status: 'success'
|
|
3450
|
+
result: T
|
|
3451
|
+
timestamp: string | number
|
|
3452
|
+
}
|
|
3453
|
+
```
|
|
3454
|
+
|
|
3455
|
+
**说明:**
|
|
3456
|
+
- 所有 HTTP 方法(get、post、put、delete)和业务方法(action、getAttributes 等)成功时返回此类型
|
|
3457
|
+
- `result` 字段包含实际的业务数据
|
|
3458
|
+
- `status` 始终为 `'success'`
|
|
3459
|
+
- `timestamp` 包含服务器响应的时间戳
|
|
3460
|
+
|
|
3461
|
+
**使用示例:**
|
|
3462
|
+
```typescript
|
|
3463
|
+
const response = await apiClient.action<User>('get_user', { user_id: 123 })
|
|
3464
|
+
console.log(response.status) // 'success'
|
|
3465
|
+
console.log(response.result) // User 对象
|
|
3466
|
+
console.log(response.timestamp) // 时间戳
|
|
3467
|
+
```
|
|
3468
|
+
|
|
3469
|
+
#### ErrorResponse - 错误响应
|
|
3470
|
+
|
|
3471
|
+
```typescript
|
|
3472
|
+
interface ErrorResponse<T> {
|
|
3473
|
+
status: 'error'
|
|
3474
|
+
code: string
|
|
3475
|
+
error_tpye: string
|
|
3476
|
+
message: string
|
|
3477
|
+
timestamp: string | number
|
|
3478
|
+
result?: T
|
|
3479
|
+
originError?: Error
|
|
3480
|
+
}
|
|
3481
|
+
```
|
|
3482
|
+
|
|
3483
|
+
**说明:**
|
|
3484
|
+
- 请求失败时会抛出此类型的异常
|
|
3485
|
+
- `code` 包含错误代码(如 'UNAUTHORIZED'、'NOT_FOUND' 等)
|
|
3486
|
+
- `error_tpye` 包含错误类型(如 'HTTP_ERROR'、'NETWORK_ERROR' 等)
|
|
3487
|
+
- `message` 包含国际化的错误消息
|
|
3488
|
+
- `originError` 包含原始的错误对象
|
|
3489
|
+
|
|
3490
|
+
**使用示例:**
|
|
3491
|
+
```typescript
|
|
3492
|
+
try {
|
|
3493
|
+
const response = await apiClient.action('some_action')
|
|
3494
|
+
console.log(response.result)
|
|
3495
|
+
} catch (error: any) {
|
|
3496
|
+
if (error.status === 'error') {
|
|
3497
|
+
console.error('错误代码:', error.code)
|
|
3498
|
+
console.error('错误消息:', error.message)
|
|
3499
|
+
}
|
|
3500
|
+
}
|
|
3501
|
+
```
|
|
3502
|
+
|
|
3503
|
+
#### RequestMetadata - 请求元数据
|
|
3504
|
+
|
|
3505
|
+
```typescript
|
|
3506
|
+
interface RequestMetadata {
|
|
3507
|
+
suppressError?: boolean // 是否抑制错误提示
|
|
3508
|
+
}
|
|
3509
|
+
```
|
|
3510
|
+
|
|
3511
|
+
**说明:**
|
|
3512
|
+
- 用于配置请求的元数据选项
|
|
3513
|
+
- `suppressError` 为 `true` 时,不自动弹出错误提示
|
|
3514
|
+
|
|
3515
|
+
**使用示例:**
|
|
3516
|
+
```typescript
|
|
3517
|
+
// 在请求配置中使用
|
|
3518
|
+
await apiClient.post('/api/data', data, {
|
|
3519
|
+
metadata: { suppressError: true }
|
|
3520
|
+
})
|
|
3521
|
+
|
|
3522
|
+
// 抑制 action 方法的错误提示
|
|
3523
|
+
await apiClient.action('some_action', params, {
|
|
3524
|
+
metadata: { suppressError: true }
|
|
3525
|
+
})
|
|
3526
|
+
```
|
|
3527
|
+
|
|
3528
|
+
### User 类型
|
|
3529
|
+
|
|
3530
|
+
```typescript
|
|
3531
|
+
interface User {
|
|
3532
|
+
id: number
|
|
3533
|
+
name: string
|
|
3534
|
+
email: string
|
|
3535
|
+
age?: number
|
|
3536
|
+
created_at: string
|
|
3537
|
+
updated_at?: string
|
|
3538
|
+
}
|
|
3539
|
+
```
|
|
3540
|
+
|
|
3541
|
+
### Task 类型
|
|
3542
|
+
|
|
3543
|
+
```typescript
|
|
3544
|
+
interface Task {
|
|
3545
|
+
id: number
|
|
3546
|
+
title: string
|
|
3547
|
+
description?: string
|
|
3548
|
+
completed?: boolean
|
|
3549
|
+
priority?: 1 | 2 | 3 | 4 | 5
|
|
3550
|
+
user_id?: number
|
|
3551
|
+
created_at?: string
|
|
3552
|
+
updated_at?: string
|
|
3553
|
+
}
|
|
3554
|
+
```
|
|
3555
|
+
|
|
3556
|
+
### 工具类型
|
|
3557
|
+
|
|
3558
|
+
#### DeepPartial - 深度可选类型
|
|
3559
|
+
|
|
3560
|
+
```typescript
|
|
3561
|
+
type DeepPartial<T> = {
|
|
3562
|
+
[P in keyof T]?: T[P] extends object
|
|
3563
|
+
? T[P] extends Array<infer U>
|
|
3564
|
+
? Array<DeepPartial<U>>
|
|
3565
|
+
: DeepPartial<T[P]>
|
|
3566
|
+
: T[P]
|
|
3567
|
+
}
|
|
3568
|
+
```
|
|
3569
|
+
|
|
3570
|
+
**说明:**
|
|
3571
|
+
- 递归地将对象的所有嵌套属性变为可选属性
|
|
3572
|
+
- 对数组类型也会递归处理数组元素的类型
|
|
3573
|
+
- 主要用于 Store 的 `setState` 方法,支持部分更新
|
|
3574
|
+
|
|
3575
|
+
**使用示例:**
|
|
3576
|
+
|
|
3577
|
+
```typescript
|
|
3578
|
+
interface User {
|
|
3579
|
+
name: string
|
|
3580
|
+
profile: {
|
|
3581
|
+
age: number
|
|
3582
|
+
address: {
|
|
3583
|
+
city: string
|
|
3584
|
+
country: string
|
|
3585
|
+
}
|
|
3586
|
+
}
|
|
3587
|
+
}
|
|
3588
|
+
|
|
3589
|
+
// 所有属性都是可选的
|
|
3590
|
+
const partial: DeepPartial<User> = {
|
|
3591
|
+
profile: {
|
|
3592
|
+
address: {
|
|
3593
|
+
city: 'Beijing' // 只更新 city,其他属性可省略
|
|
3594
|
+
}
|
|
3595
|
+
}
|
|
3596
|
+
}
|
|
3597
|
+
|
|
3598
|
+
// 在 Store 中使用
|
|
3599
|
+
store.setState(partial) // TypeScript 类型检查通过
|
|
3600
|
+
```
|
|
3601
|
+
|
|
3602
|
+
### 常量和枚举
|
|
3603
|
+
|
|
3604
|
+
```typescript
|
|
3605
|
+
import {
|
|
3606
|
+
// 存储键名常量
|
|
3607
|
+
TOKEN_KEY, // 'rigol_token'
|
|
3608
|
+
|
|
3609
|
+
// 场景类型枚举
|
|
3610
|
+
SceneType, // { STANDALONE, ELECTRON_BROWSERWINDOW, ELECTRON_WEBCONTENTSVIEW }
|
|
3611
|
+
|
|
3612
|
+
// WebSocket 消息类型枚举
|
|
3613
|
+
WsMessageType, // { SNAPSHOT: 'attribute_snapshot', CHANGE: 'attribute_change' }
|
|
3614
|
+
|
|
3615
|
+
// WebSocket 状态枚举
|
|
3616
|
+
WebSocketState, // { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 }
|
|
3617
|
+
|
|
3618
|
+
// 平台应用 ID 常量对象
|
|
3619
|
+
PLATFORM_INTERNAL_APPIDS
|
|
3620
|
+
} from '@openuverse/uvapi'
|
|
3621
|
+
```
|
|
3622
|
+
|
|
3623
|
+
### 导入类型
|
|
3624
|
+
|
|
3625
|
+
```typescript
|
|
3626
|
+
import type {
|
|
3627
|
+
// API 响应类型
|
|
3628
|
+
Response,
|
|
3629
|
+
ErrorResponse,
|
|
3630
|
+
RequestMetadata,
|
|
3631
|
+
|
|
3632
|
+
// 业务类型
|
|
3633
|
+
User,
|
|
3634
|
+
Task,
|
|
3635
|
+
|
|
3636
|
+
// 配置类型
|
|
3637
|
+
RestAPIConfig,
|
|
3638
|
+
WebSocketConfig,
|
|
3639
|
+
PluginOptions,
|
|
3640
|
+
AppBaseConfig,
|
|
3641
|
+
|
|
3642
|
+
// Store 类型
|
|
3643
|
+
Store,
|
|
3644
|
+
StoreOptions,
|
|
3645
|
+
DeepPartial,
|
|
3646
|
+
|
|
3647
|
+
// 平台类型
|
|
3648
|
+
PlatformAppId,
|
|
3649
|
+
|
|
3650
|
+
// WebSocket 类型
|
|
3651
|
+
WebSocketMessage,
|
|
3652
|
+
WebSocketEventType
|
|
3653
|
+
} from '@openuverse/uvapi'
|
|
3654
|
+
```
|
|
3655
|
+
|
|
3656
|
+
---
|
|
3657
|
+
|
|
3658
|
+
## 🔌 拦截器
|
|
3659
|
+
|
|
3660
|
+
UV-API 内置了请求和响应拦截器:
|
|
3661
|
+
|
|
3662
|
+
### 请求拦截器
|
|
3663
|
+
- 自动记录请求信息(方法和 URL)
|
|
3664
|
+
- 统一错误处理和类型转换
|
|
3665
|
+
|
|
3666
|
+
### 响应拦截器
|
|
3667
|
+
- 自动记录响应信息(状态码、URL 和数据)
|
|
3668
|
+
- 统一错误处理:
|
|
3669
|
+
- HTTP 错误状态码处理
|
|
3670
|
+
- 网络连接错误处理
|
|
3671
|
+
- 请求配置错误处理
|
|
3672
|
+
|
|
3673
|
+
---
|
|
3674
|
+
|
|
3675
|
+
## 🔧 开发
|
|
3676
|
+
|
|
3677
|
+
### 安装依赖
|
|
3678
|
+
|
|
3679
|
+
```bash
|
|
3680
|
+
npm install
|
|
3681
|
+
```
|
|
3682
|
+
|
|
3683
|
+
### 构建
|
|
3684
|
+
|
|
3685
|
+
```bash
|
|
3686
|
+
# 构建库文件
|
|
3687
|
+
npm run build
|
|
3688
|
+
|
|
3689
|
+
# 构建并打包
|
|
3690
|
+
npm run build:tgz
|
|
3691
|
+
```
|
|
3692
|
+
|
|
3693
|
+
### 代码质量
|
|
3694
|
+
|
|
3695
|
+
```bash
|
|
3696
|
+
# TypeScript 类型检查
|
|
3697
|
+
npm run type-check
|
|
3698
|
+
|
|
3699
|
+
# 代码检查
|
|
3700
|
+
npm run lint
|
|
3701
|
+
|
|
3702
|
+
# 代码检查(自动修复)
|
|
3703
|
+
npm run lint
|
|
3704
|
+
|
|
3705
|
+
# 代码格式化
|
|
3706
|
+
npm run format
|
|
3707
|
+
```
|
|
3708
|
+
|
|
3709
|
+
### 发布
|
|
3710
|
+
|
|
3711
|
+
```bash
|
|
3712
|
+
# 发布到内部 npm registry
|
|
3713
|
+
npm run pub
|
|
3714
|
+
```
|
|
3715
|
+
|
|
3716
|
+
发布脚本会自动:
|
|
3717
|
+
1. 执行构建
|
|
3718
|
+
2. 登录到内部 npm registry(`https://registry.npmjs.org/`)
|
|
3719
|
+
3. 发布包
|
|
3720
|
+
|
|
3721
|
+
---
|
|
3722
|
+
|
|
3723
|
+
## 📂 项目结构
|
|
3724
|
+
|
|
3725
|
+
```
|
|
3726
|
+
rigol-uv-api/
|
|
3727
|
+
├── src/
|
|
3728
|
+
│ ├── api/ # API 客户端
|
|
3729
|
+
│ │ ├── modules/ # 业务模块
|
|
3730
|
+
│ │ │ ├── index.ts # 模块导出
|
|
3731
|
+
│ │ │ ├── user.ts # 用户管理客户端
|
|
3732
|
+
│ │ │ └── task.ts # 任务管理客户端
|
|
3733
|
+
│ │ ├── RestAPIClient.ts # 基础 REST 客户端
|
|
3734
|
+
│ │ ├── WebSocketClient.ts # WebSocket 客户端
|
|
3735
|
+
│ │ └── index.ts # API 模块入口
|
|
3736
|
+
│ ├── config/ # 配置管理
|
|
3737
|
+
│ │ └── index.ts # 配置初始化和平台应用 ID 常量
|
|
3738
|
+
│ ├── hooks/ # Vue Hooks
|
|
3739
|
+
│ │ ├── index.ts # Hooks 导出
|
|
3740
|
+
│ │ └── useAttributeMonitor.ts # WebSocket 属性监听 Hook
|
|
3741
|
+
│ ├── locale/ # 国际化
|
|
3742
|
+
│ │ ├── index.ts # 国际化配置和初始化
|
|
3743
|
+
│ │ ├── zh-CN.ts # 中文语言包
|
|
3744
|
+
│ │ └── en-US.ts # 英文语言包
|
|
3745
|
+
│ ├── preload/ # Electron Preload 功能
|
|
3746
|
+
│ │ └── index.ts # Preload 工具函数(getMainProcessArgs、initMandatoryUVerseAPI)
|
|
3747
|
+
│ ├── store/ # 状态管理
|
|
3748
|
+
│ │ ├── index.ts # Store 导出
|
|
3749
|
+
│ │ └── storeFactory.ts # Store 工厂函数和管理器
|
|
3750
|
+
│ ├── theme/ # 主题管理
|
|
3751
|
+
│ │ └── index.ts # 主题初始化和事件监听
|
|
3752
|
+
│ ├── types/ # 类型定义
|
|
3753
|
+
│ │ ├── global.d.ts # 全局类型定义(Window、Axios 扩展)
|
|
3754
|
+
│ │ └── index.ts # 类型导出(DeepPartial、配置类型等)
|
|
3755
|
+
│ ├── utils/ # 工具函数
|
|
3756
|
+
│ │ ├── constance.ts # 常量定义(TOKEN_KEY、SceneType、WsMessageType)
|
|
3757
|
+
│ │ └── index.ts # 工具函数导出(存储管理、场景检测、深拷贝、深度合并、MessagePack 解码等)
|
|
3758
|
+
│ └── index.ts # 库主入口
|
|
3759
|
+
├── dist/ # 构建输出
|
|
3760
|
+
│ ├── rigol-uv-api.js # ES Module 格式
|
|
3761
|
+
│ ├── rigol-uv-api.umd.cjs # UMD 格式
|
|
3762
|
+
│ └── index.d.ts # 类型声明文件
|
|
3763
|
+
├── CHANGELOG.md # 更新日志
|
|
3764
|
+
├── eslint.config.js # ESLint 配置
|
|
3765
|
+
├── tsconfig.json # TypeScript 配置
|
|
3766
|
+
├── vite.config.ts # Vite 构建配置
|
|
3767
|
+
├── package.json # 项目配置
|
|
3768
|
+
└── README.md # 项目文档
|
|
3769
|
+
```
|
|
3770
|
+
|
|
3771
|
+
---
|
|
3772
|
+
|
|
3773
|
+
## 🎯 使用场景
|
|
3774
|
+
|
|
3775
|
+
### 在 Vue 3 组件中使用
|
|
3776
|
+
|
|
3777
|
+
```vue
|
|
3778
|
+
<template>
|
|
3779
|
+
<div>
|
|
3780
|
+
<button @click="fetchUsers">获取用户列表</button>
|
|
3781
|
+
<button @click="createTask">创建任务</button>
|
|
3782
|
+
</div>
|
|
3783
|
+
</template>
|
|
3784
|
+
|
|
3785
|
+
<script setup lang="ts">
|
|
3786
|
+
import { ref } from 'vue'
|
|
3787
|
+
import { UserClient, TaskClient } from '@openuverse/uvapi'
|
|
3788
|
+
|
|
3789
|
+
const userClient = new UserClient({
|
|
3790
|
+
baseURL: 'https://api.example.com'
|
|
3791
|
+
})
|
|
3792
|
+
|
|
3793
|
+
const taskClient = new TaskClient({
|
|
3794
|
+
baseURL: 'https://api.example.com'
|
|
3795
|
+
})
|
|
3796
|
+
|
|
3797
|
+
const fetchUsers = async () => {
|
|
3798
|
+
try {
|
|
3799
|
+
const response = await userClient.get_users()
|
|
3800
|
+
const users = response.result
|
|
3801
|
+
console.log('用户列表:', users)
|
|
3802
|
+
} catch (error) {
|
|
3803
|
+
console.error('获取失败:', error)
|
|
3804
|
+
}
|
|
3805
|
+
}
|
|
3806
|
+
|
|
3807
|
+
const createTask = async () => {
|
|
3808
|
+
try {
|
|
3809
|
+
const response = await taskClient.create_task({
|
|
3810
|
+
title: '新任务',
|
|
3811
|
+
description: '任务描述',
|
|
3812
|
+
priority: 1
|
|
3813
|
+
})
|
|
3814
|
+
const task = response.result
|
|
3815
|
+
console.log('创建成功:', task)
|
|
3816
|
+
} catch (error) {
|
|
3817
|
+
console.error('创建失败:', error)
|
|
3818
|
+
}
|
|
3819
|
+
}
|
|
3820
|
+
</script>
|
|
3821
|
+
```
|
|
3822
|
+
|
|
3823
|
+
### 在 TypeScript 项目中使用
|
|
3824
|
+
|
|
3825
|
+
```typescript
|
|
3826
|
+
import { UserClient, type User } from '@openuverse/uvapi'
|
|
3827
|
+
|
|
3828
|
+
class UserService {
|
|
3829
|
+
private client: UserClient
|
|
3830
|
+
|
|
3831
|
+
constructor() {
|
|
3832
|
+
this.client = new UserClient({
|
|
3833
|
+
baseURL: process.env.API_BASE_URL,
|
|
3834
|
+
timeout: 10000
|
|
3835
|
+
})
|
|
3836
|
+
}
|
|
3837
|
+
|
|
3838
|
+
async getAllUsers(): Promise<User[]> {
|
|
3839
|
+
const response = await this.client.get_users()
|
|
3840
|
+
return response.result
|
|
3841
|
+
}
|
|
3842
|
+
|
|
3843
|
+
async getUserById(id: number): Promise<User> {
|
|
3844
|
+
const response = await this.client.get_user({ user_id: id })
|
|
3845
|
+
return response.result
|
|
3846
|
+
}
|
|
3847
|
+
|
|
3848
|
+
async createUser(data: Omit<User, 'id' | 'created_at'>): Promise<User> {
|
|
3849
|
+
const response = await this.client.create_user(data)
|
|
3850
|
+
return response.result
|
|
3851
|
+
}
|
|
3852
|
+
}
|
|
3853
|
+
```
|
|
3854
|
+
|
|
3855
|
+
---
|
|
3856
|
+
|
|
3857
|
+
## 🤝 贡献
|
|
3858
|
+
|
|
3859
|
+
欢迎提交 Issue 和 Pull Request!
|
|
3860
|
+
|
|
3861
|
+
---
|
|
3862
|
+
|
|
3863
|
+
## 📄 许可证
|
|
3864
|
+
|
|
3865
|
+
MIT License
|
|
3866
|
+
|
|
3867
|
+
---
|
|
3868
|
+
|
|
3869
|
+
## 📞 联系方式
|
|
3870
|
+
|
|
3871
|
+
如有问题或建议,请联系开发团队。
|