bjchy-udg-sdk 1.1.3 → 1.3.0
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 +70 -4
- package/package.json +1 -1
- package/src/auth.js +19 -3
- package/src/index.js +46 -4
- package/src/request.js +67 -1
package/README.md
CHANGED
|
@@ -55,12 +55,15 @@ const client = udg.init({ endpoint, streetKey })
|
|
|
55
55
|
// 同时传 appid 与 streetKey 时以 appid 为准,忽略 streetKey,不会调用 resolve
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
**登录(五选一)**,token 缓存 / 自动续期 / 自动重登由 SDK 内部处理:
|
|
59
59
|
|
|
60
60
|
```js
|
|
61
61
|
// ① 小程序:自动 wx.login(需在管理后台为该 appid 配置微信 AppSecret)
|
|
62
62
|
const { token, openId } = await client.login() // openId 同时写入 JWT;非小程序环境无 openId
|
|
63
63
|
|
|
64
|
+
// ①b web-view 内的 H5:拿不到 wx.login,由宿主小程序传 code 进来(详见下方「web-view 内 H5 的登录」)
|
|
65
|
+
const { token, openId } = await client.login({ code })
|
|
66
|
+
|
|
64
67
|
// ② Node / 脚本:apiKey 登录(apiKey 按 appid 在管理后台配置,放环境变量)
|
|
65
68
|
await client.login({ apiKey: process.env.UDG_API_KEY })
|
|
66
69
|
|
|
@@ -95,6 +98,28 @@ const { status, token } = await client.checkScanLogin(sessionId)
|
|
|
95
98
|
|
|
96
99
|
辅助方法:`isLoggedIn()` / `getToken()` / `setToken(t)` / `logout()` / `getStreetKey()` / `buildScanQrContent(sessionId, opts?)` / `checkScanLogin(sessionId, opts?)`(单次校验,不轮询)/ `getScanSessionFromUrl(opts?)`(从 URL 读 sid,不发请求)/ `tryLoginFromUrl(opts?)`(组合入口,等价旧包 `checkUrlSessionAndLogin`)。
|
|
97
100
|
|
|
101
|
+
### web-view 内 H5 的登录(传 code,不传 token)
|
|
102
|
+
|
|
103
|
+
小程序 `<web-view>` 里的 H5 属于 Web 环境,没有 `wx.login`。**正确做法是宿主小程序只把微信登录 code 传给 H5,由 H5 自己换 token**——code 5 分钟有效且一次性,即使随 URL 落进浏览器历史/日志也基本无害;换回的是完整 token + refreshToken,享受 SDK 的自动续期。
|
|
104
|
+
|
|
105
|
+
```js
|
|
106
|
+
// 小程序中转页:只做一件事,不碰 UDG
|
|
107
|
+
const { code } = await wx.login()
|
|
108
|
+
wx.navigateTo({ url: `/pages/webview/index?c=${code}` })
|
|
109
|
+
// 页面内:<web-view src="https://h5.example.cn/page?c={{code}}" />
|
|
110
|
+
|
|
111
|
+
// H5 侧:
|
|
112
|
+
const client = udg.init({ endpoint, appid }) // appid 必须与宿主小程序一致
|
|
113
|
+
await client.login({ code: new URLSearchParams(location.search).get('c') })
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
注意事项:
|
|
117
|
+
|
|
118
|
+
- **不要改传 token**:URL 里的长效 JWT 在有效期内可被完全冒充,且 `init({ token })` 是 external 模式,SDK 不为它续期、过期即失效。
|
|
119
|
+
- **页面刷新**:`login()` 幂等,缓存 token 未过期时直接复用,不会再用已废的 code;前提是 H5 每次 `init` 传的 `appid` 一致(token 存储键依赖它)。
|
|
120
|
+
- **refreshToken 也过期时**:H5 拿不到新 code,SDK 的自动重登会返回失败并抛鉴权错误(这是预期行为)。业务兜底:`wx.miniProgram.redirectTo` 回中转页重取 code。注意 `wx.miniProgram.postMessage` **不是实时的**(小程序只在分享/复制链接/后退/组件销毁时才收到),不能用它通知小程序。
|
|
121
|
+
- **CORS**:H5 域名需在 Gateway 的跨域白名单里。
|
|
122
|
+
|
|
98
123
|
**openId 约定**:JWT 内统一字段名为 `openId`(小程序 `wx.login`、网页扫码、外部 MGAPIV3 token 均如此)。小程序 `login()` 成功时响应含 `openId`;扫码登录的 `openId` 在 JWT 中,业务侧一般从 `userInfo` 或解码 token 读取。
|
|
99
124
|
|
|
100
125
|
envId / mongoDatabase / AppSecret 由服务端从 `wxdb.config` 读取,客户端不传、不可传。
|
|
@@ -143,7 +168,7 @@ const { data: [doc] } = await db.collection('users').doc(id).get()
|
|
|
143
168
|
// 单条 → { _id }
|
|
144
169
|
const { _id } = await db.collection('users').add({ data: { name: 'alice', createdAt: new Date() } })
|
|
145
170
|
|
|
146
|
-
// 批量(≤
|
|
171
|
+
// 批量(≤5000 条,一次事务:要么全部成功,要么全部回退)→ { ids }
|
|
147
172
|
const { ids } = await db.collection('users').add({ data: [{...}, {...}] })
|
|
148
173
|
|
|
149
174
|
// 更新(where 匹配全部;doc(id) 单条)
|
|
@@ -157,6 +182,27 @@ await db.collection('users').doc(id).remove()
|
|
|
157
182
|
|
|
158
183
|
用户登录(非 apiKey)时,Gateway 在 `add` 时自动写入 `_openid`(取自 token 的 `openId`,覆盖客户端传入值);`apiKey` 登录不注入,无需在 `data` 里手动传 `_openid`。
|
|
159
184
|
|
|
185
|
+
### 批量写入的事务保证(≤5000 条)
|
|
186
|
+
|
|
187
|
+
传数组时 Gateway **在一个事务里整批提交**:任一条失败,整批都不落库,不会出现"前 800 条写进去了、第 801 条报错"的半截状态。四类数据源都是如此(MongoDB / CloudBase 用事务包住批量插入,MySQL / Oracle 本来就在事务内逐条 INSERT)。
|
|
188
|
+
|
|
189
|
+
```js
|
|
190
|
+
try {
|
|
191
|
+
const { ids } = await db.collection('coupon').add({ data: bigArray }) // bigArray.length <= 5000
|
|
192
|
+
// 走到这里 = 5000 条全部落库,ids 与入参一一对应
|
|
193
|
+
} catch (e) {
|
|
194
|
+
// 走到这里 = 一条都没落库,直接整批重试即可,不必先查"写进去几条"
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
注意事项:
|
|
199
|
+
|
|
200
|
+
- **超过 5000 条自行分批**,每批仍各自是一个事务(跨批没有全局事务,批与批之间可能一批成功一批失败)。
|
|
201
|
+
- **请求体大小才是真正的瓶颈**:网关限 20MB,其上游 nginx 也须放开(本项目 `pdb.bjchy.gov.cn/udg` 已配 20MB)。5000 条 × 400 字节 ≈ 2MB。413 报错就是撞到了这道闸门。
|
|
202
|
+
- **大批量请调大超时**:`udg.init({ endpoint, appid, timeout: 60000 })`。SDK 默认 15s,弱网上传几 MB 可能不够;**客户端超时不等于服务端回滚**——服务端可能仍在提交,超时后应先查再重试,别盲目重发。
|
|
203
|
+
- MongoDB 数据源需要副本集(本项目 `rs0` 满足)。非副本集实例会直接报错而不是退化成部分写入。
|
|
204
|
+
- 批量 > 200 条时,SSE `watch()` 收到的事件不再携带文档内容,只给 `documentIds` 与 `truncated: true`(避免把订阅端打爆),需要内容请自行重查。
|
|
205
|
+
|
|
160
206
|
更新指令:`set remove inc mul push pop shift unshift addToSet pull pullAll`;也可传原生 update 文档(顶层全 `$` 键时直传,如 `{ $set: {...}, $inc: {...} }`)。
|
|
161
207
|
|
|
162
208
|
## 聚合(重点能力)
|
|
@@ -202,14 +248,34 @@ body: { "db": "<dbKey>", "collection": "<表名>" }
|
|
|
202
248
|
|
|
203
249
|
**配套 MCP Server**(UDG 仓库 `mcp/` 目录):只读工具 `udg_list_collections`(列可访问的表)、`udg_describe_collection`(查表结构)、`udg_query` / `udg_aggregate`(只读试查询)、`udg_nl_query`(自然语言查询),环境变量 `UDG_ENDPOINT` / `UDG_APPID` / `UDG_APIKEY`,适合接入 Claude Code / Cursor 等 AI 开发工具。
|
|
204
250
|
|
|
251
|
+
## 服务端时间(防本机时钟篡改)
|
|
252
|
+
|
|
253
|
+
Gateway 的**每个响应都带 `timestamp`**,SDK 据此被动维护本地时钟偏差。凡是"是否已截止""是否已过期"这类判断,**一律用 `client.now()` 而不是 `new Date()`** —— 用户改本机时间不会影响结果。
|
|
254
|
+
|
|
255
|
+
```js
|
|
256
|
+
client.now() // → Date,服务端校正后的当前时间
|
|
257
|
+
client.serverTimeOffset() // → 毫秒,本地相对服务端的偏差(正数 = 本地慢)
|
|
258
|
+
client.lastTimeSyncAt() // → 最近一次对时的本地时刻(毫秒时间戳),0 = 从未对时
|
|
259
|
+
await client.syncTime() // → 主动对时(GET /health,无需登录),返回偏差
|
|
260
|
+
|
|
261
|
+
// 典型用法:判断活动是否还在报名期
|
|
262
|
+
if (client.now() < new Date(activity.bookEnd)) { /* 可以报名 */ }
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
发生过**任意一次请求(含 `login()`、含失败的请求)**之后 `now()` 即为可信时间,常规业务无需显式对时。仅当"页面刚打开、还没发过任何请求就要判断时效"时才需要先 `await client.syncTime()`。从未对过时会退化为本地时间(不抛错)。
|
|
266
|
+
|
|
267
|
+
基准取请求前后本地时间的中点,抵消约一半网络往返;剩余误差在毫秒~百毫秒量级,而本能力要防的是"改本机时间"这种小时量级的偏差。
|
|
268
|
+
|
|
269
|
+
> 注意与 `db.serverDate()` 的区别:后者是写入数据时的日期值,V1 以客户端时间近似;需要**不可伪造**的写入时间请在 Gateway 侧配 `beforeWrite.autoTimestamps` 钩子。
|
|
270
|
+
|
|
205
271
|
## 返回与错误
|
|
206
272
|
|
|
207
273
|
返回兼容微信云开发:`get → {data}`、`count → {total}`、`aggregate → {list}`、`add → {_id}/{ids}`、`update → {stats:{updated}}`、`remove → {stats:{removed}}`。
|
|
208
274
|
|
|
209
|
-
失败抛统一错误对象:`{ errorCode, errorMessage, requestId, timestamp }`(如 `UNSUPPORTED_OPERATOR`、`TENANT_NOT_FOUND`、`DB_NOT_FOUND`(dbKey 未在租户 bindings[] 中登记)、`READONLY_DATABASE`(对只读 dbKey 或表级只读的表执行了写操作)、`TABLE_ACCESS_DENIED`(表被租户表级权限拒绝:例外模式 denied 的表 / 白名单模式未列出的表,含聚合 `$lookup` 引用的表)、`FORBIDDEN`(Token 无效/过期,会自动 refresh 重试)、`TIMEOUT`)。
|
|
275
|
+
失败抛统一错误对象:`{ errorCode, errorMessage, requestId, timestamp }`(如 `UNSUPPORTED_OPERATOR`、`TENANT_NOT_FOUND`、`DB_NOT_FOUND`(dbKey 未在租户 bindings[] 中登记)、`READONLY_DATABASE`(对只读 dbKey 或表级只读的表执行了写操作)、`APPEND_ONLY_TABLE`(表被设为 `append` 只增表,只能 `add`,不能 `update`/`remove`)、`TABLE_ACCESS_DENIED`(表被租户表级权限拒绝:例外模式 denied 的表 / 白名单模式未列出的表,含聚合 `$lookup` 引用的表)、`FORBIDDEN`(Token 无效/过期,会自动 refresh 重试)、`TIMEOUT`)。
|
|
210
276
|
|
|
211
277
|
## 说明
|
|
212
278
|
|
|
213
279
|
- 日期:SDK 与 Gateway 以 `{ $date: 毫秒 }` 传输,业务代码直接用 `Date` 对象读写即可
|
|
214
|
-
- `db.serverDate()` V1
|
|
280
|
+
- `db.serverDate()` V1 以客户端时间近似;需要可信的“当前时间”用 `client.now()`,需要不可伪造的“写入时间”用 Gateway 的 `beforeWrite.autoTimestamps` 钩子
|
|
215
281
|
- distinct / 文件上传:V1 不提供
|
package/package.json
CHANGED
package/src/auth.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* AuthManager:token 全生命周期管理(SDK 内部,业务无感)。
|
|
3
|
-
* - 登录:wx.login(小程序)/ apiKey(Node/Web/脚本)/ 扫码 / 外部 token 直入
|
|
3
|
+
* - 登录:wx.login(小程序)/ 外部传入的微信 code(web-view 内 H5)/ apiKey(Node/Web/脚本)/ 扫码 / 外部 token 直入
|
|
4
4
|
* - 持久化缓存:未过期不重复登录
|
|
5
5
|
* - 自动续期:请求 403 时用 refreshToken 换新并重试(见 request.js)
|
|
6
6
|
* - 自动重登:refresh 失效且为微信登录模式时,自动重新 wx.login
|
|
@@ -136,6 +136,7 @@ class AuthManager {
|
|
|
136
136
|
/**
|
|
137
137
|
* 登录(幂等:缓存 token 未过期时直接复用,force 可强制重登)。
|
|
138
138
|
* - login():小程序环境自动 wx.login
|
|
139
|
+
* - login({ code }):用外部拿到的微信登录 code 换 token(web-view 内 H5:由宿主小程序 wx.login 后经 URL 传入)
|
|
139
140
|
* - login({ apiKey }):密钥登录
|
|
140
141
|
*/
|
|
141
142
|
async login(opts) {
|
|
@@ -145,6 +146,14 @@ class AuthManager {
|
|
|
145
146
|
const payload = decodeJwtPayload(this.token)
|
|
146
147
|
return { token: this.token, openId: payload && payload.openId, cached: true }
|
|
147
148
|
}
|
|
149
|
+
// 外部传入的微信 code(web-view 内 H5 等拿不到 wx.login 的环境);与小程序内登录同一端点,
|
|
150
|
+
// 换回的是完整 token + refreshToken,因此后续可自动续期,不同于 external token 直入。
|
|
151
|
+
if (o.code) {
|
|
152
|
+
const data = await this.rawPost('/auth/wxlogin', { appid: this.ctx.appid, code: o.code })
|
|
153
|
+
this.openId = data.openId
|
|
154
|
+
this.setTokens(data.token, data.refreshToken, 'wechat')
|
|
155
|
+
return { token: this.token, openId: data.openId, cached: false }
|
|
156
|
+
}
|
|
148
157
|
if (this._apiKey) {
|
|
149
158
|
const data = await this.rawPost('/auth/login', { appid: this.ctx.appid, apiKey: this._apiKey })
|
|
150
159
|
this.setTokens(data.token, data.refreshToken, 'apikey')
|
|
@@ -157,7 +166,10 @@ class AuthManager {
|
|
|
157
166
|
this.setTokens(data.token, data.refreshToken, 'wechat')
|
|
158
167
|
return { token: this.token, openId: data.openId, cached: false }
|
|
159
168
|
}
|
|
160
|
-
throw new Error(
|
|
169
|
+
throw new Error(
|
|
170
|
+
'login 在非小程序环境需要 apiKey 参数,或传 code(web-view 内 H5:由宿主小程序 wx.login 取得后经 URL 传入);' +
|
|
171
|
+
'在微信小程序环境中则自动使用 wx.login'
|
|
172
|
+
)
|
|
161
173
|
}
|
|
162
174
|
|
|
163
175
|
/** 用 refreshToken 续期;成功返回 true */
|
|
@@ -172,7 +184,11 @@ class AuthManager {
|
|
|
172
184
|
}
|
|
173
185
|
}
|
|
174
186
|
|
|
175
|
-
/**
|
|
187
|
+
/**
|
|
188
|
+
* 续期失败后的自动重登(仅微信小程序 / apiKey 模式可行)。
|
|
189
|
+
* web-view 内 H5 用 code 登录后 mode 同为 'wechat',但拿不到新 code,这里返回 false 由业务兜底
|
|
190
|
+
* (通常是 wx.miniProgram.redirectTo 回中转页重取 code)。
|
|
191
|
+
*/
|
|
176
192
|
async relogin() {
|
|
177
193
|
if (this.mode === 'wechat' && isMiniProgram()) {
|
|
178
194
|
await this.login({ force: true })
|
package/src/index.js
CHANGED
|
@@ -7,8 +7,9 @@
|
|
|
7
7
|
* // Web 多租户场景可只传 streetKey(appid 与 streetKey 二选一,同传以 appid 为准):
|
|
8
8
|
* // udg.init({ endpoint, streetKey: 'hjl' })
|
|
9
9
|
*
|
|
10
|
-
*
|
|
10
|
+
* 登录(五选一):
|
|
11
11
|
* await client.login() // 小程序:自动 wx.login 换 token
|
|
12
|
+
* await client.login({ code }) // web-view 内 H5:宿主小程序 wx.login 后经 URL 传入的 code
|
|
12
13
|
* await client.login({ apiKey }) // Node / 脚本 / Web:appid 级密钥
|
|
13
14
|
* await client.pollScanLogin(sessionId) // Web:扫码登录(配合 createScanSession)
|
|
14
15
|
* udg.init({ ..., token }) // 外部体系已有 JWT 直入
|
|
@@ -19,7 +20,7 @@
|
|
|
19
20
|
*/
|
|
20
21
|
const { Database } = require('./database')
|
|
21
22
|
const { command, UdgRegExp } = require('./command')
|
|
22
|
-
const { rawPost, postAuthed, UdgRequestError } = require('./request')
|
|
23
|
+
const { rawPost, postAuthed, fetchServerTime, UdgRequestError } = require('./request')
|
|
23
24
|
const { AuthManager } = require('./auth')
|
|
24
25
|
const { AiNamespace } = require('./ai')
|
|
25
26
|
const storage = require('./storage')
|
|
@@ -107,8 +108,13 @@ class UdgClient {
|
|
|
107
108
|
/* ===================== 认证 ===================== */
|
|
108
109
|
|
|
109
110
|
/**
|
|
110
|
-
* 登录。小程序环境无参调用(自动 wx.login);其他环境传 { apiKey }。
|
|
111
|
-
*
|
|
111
|
+
* 登录。小程序环境无参调用(自动 wx.login);其他环境传 { apiKey } 或 { code }。
|
|
112
|
+
*
|
|
113
|
+
* `{ code }`:web-view 内的 H5 拿不到 `wx.login`,由宿主小程序中转页 `wx.login()` 取 code 后
|
|
114
|
+
* 经 web-view URL 传进来(code 5 分钟一次性,泄露风险远低于传 token),换回的是完整
|
|
115
|
+
* token + refreshToken,可自动续期。
|
|
116
|
+
*
|
|
117
|
+
* 幂等:本地缓存 token 未过期时直接复用(页面刷新时 code 已废也不受影响);{ force: true } 强制重登。
|
|
112
118
|
*/
|
|
113
119
|
async login(opts) {
|
|
114
120
|
await ensureAppid(this._ctx)
|
|
@@ -135,6 +141,42 @@ class UdgClient {
|
|
|
135
141
|
this._ctx.auth.logout()
|
|
136
142
|
}
|
|
137
143
|
|
|
144
|
+
/* ===================== 服务端时间 ===================== */
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* 服务端校正后的当前时间。
|
|
148
|
+
*
|
|
149
|
+
* Gateway 的每个响应(成功与失败)都带 timestamp,SDK 据此被动维护本地时钟偏差,
|
|
150
|
+
* 因此发生过任意一次请求(含 login)之后本方法即为可信时间。**凡是"是否已截止""是否已过期"
|
|
151
|
+
* 这类判断都应该用它而不是 new Date()** —— 用户改本机时间不会影响结果。
|
|
152
|
+
*
|
|
153
|
+
* 尚未与服务端通信过时退化为本地时间;需要在首屏就判断时效,请先 await client.syncTime()。
|
|
154
|
+
* @returns {Date}
|
|
155
|
+
*/
|
|
156
|
+
now() {
|
|
157
|
+
return new Date(Date.now() + (this._ctx._timeOffset || 0))
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 本地时钟相对服务端的偏差(毫秒,正数 = 本地慢);从未对过时返回 0 */
|
|
161
|
+
serverTimeOffset() {
|
|
162
|
+
return this._ctx._timeOffset || 0
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 最近一次对时的本地时刻(毫秒时间戳);从未对过时返回 0 */
|
|
166
|
+
lastTimeSyncAt() {
|
|
167
|
+
return this._ctx._timeSyncedAt || 0
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* 主动与服务端对一次时(GET /health,无需登录)。
|
|
172
|
+
* 常规使用不必调用——任何一次业务请求都会自动对时;仅在"页面刚打开、还没发过任何请求
|
|
173
|
+
* 就要判断活动是否已截止"这类场景下需要显式调用。
|
|
174
|
+
* @returns {Promise<number>} 校正后的偏差(毫秒)
|
|
175
|
+
*/
|
|
176
|
+
async syncTime() {
|
|
177
|
+
return fetchServerTime(this._ctx)
|
|
178
|
+
}
|
|
179
|
+
|
|
138
180
|
/* ===================== 扫码登录(Web 端) ===================== */
|
|
139
181
|
|
|
140
182
|
/**
|
package/src/request.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* - Web / Node(>=18) → fetch
|
|
5
5
|
*
|
|
6
6
|
* 数据请求自动携带 token;遇 401/403 时自动 refresh → 重试 → 必要时自动重登(业务无感)。
|
|
7
|
+
* 每个响应(成功与失败)都带 Gateway 的 timestamp,据此被动维护本地时钟偏差,供 client.now() 使用。
|
|
7
8
|
*/
|
|
8
9
|
const { encode, decode } = require('./serialize')
|
|
9
10
|
|
|
@@ -73,15 +74,80 @@ async function requestViaFetch(url, body, headers, timeout) {
|
|
|
73
74
|
}
|
|
74
75
|
}
|
|
75
76
|
|
|
77
|
+
/* ===================== 服务端时间校正 ===================== */
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 记录本地时钟相对服务端的偏差。Gateway 的 ok()/fail() 都会返回 timestamp,
|
|
81
|
+
* 因此任何一次请求(哪怕失败)都能顺带完成对时,无需额外往返。
|
|
82
|
+
* 基准取请求前后本地时间的中点,抵消约一半网络往返;剩余误差在毫秒~百毫秒量级,
|
|
83
|
+
* 而本能力要防的是"用户改本机时间"这种小时量级的偏差,精度绰绰有余。
|
|
84
|
+
*/
|
|
85
|
+
function captureServerTime(ctx, json, t0, t1) {
|
|
86
|
+
if (!ctx || !json || !json.timestamp) return
|
|
87
|
+
const serverMs = Date.parse(json.timestamp)
|
|
88
|
+
if (!serverMs) return
|
|
89
|
+
ctx._timeOffset = serverMs - (t0 + t1) / 2
|
|
90
|
+
ctx._timeSyncedAt = t1
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function getViaWx(url, timeout) {
|
|
94
|
+
return new Promise((resolve, reject) => {
|
|
95
|
+
// eslint-disable-next-line no-undef
|
|
96
|
+
wx.request({
|
|
97
|
+
url,
|
|
98
|
+
method: 'GET',
|
|
99
|
+
timeout,
|
|
100
|
+
success: (res) => resolve(res.data),
|
|
101
|
+
fail: (err) =>
|
|
102
|
+
reject(new UdgRequestError({ errorCode: 'NETWORK_ERROR', errorMessage: err.errMsg || '网络请求失败' }))
|
|
103
|
+
})
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function getViaFetch(url, timeout) {
|
|
108
|
+
if (typeof fetch !== 'function') {
|
|
109
|
+
throw new UdgRequestError({
|
|
110
|
+
errorCode: 'ENV_NOT_SUPPORTED',
|
|
111
|
+
errorMessage: '当前环境不支持 fetch(Node 需 >= 18,或在微信小程序中使用)'
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
const controller = typeof AbortController !== 'undefined' ? new AbortController() : null
|
|
115
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeout) : null
|
|
116
|
+
try {
|
|
117
|
+
const res = await fetch(url, { method: 'GET', signal: controller ? controller.signal : undefined })
|
|
118
|
+
return await res.json()
|
|
119
|
+
} catch (err) {
|
|
120
|
+
if (err.name === 'AbortError') {
|
|
121
|
+
throw new UdgRequestError({ errorCode: 'TIMEOUT', errorMessage: `请求超时(${timeout}ms)` })
|
|
122
|
+
}
|
|
123
|
+
throw new UdgRequestError({ errorCode: 'NETWORK_ERROR', errorMessage: err.message || '网络请求失败' })
|
|
124
|
+
} finally {
|
|
125
|
+
if (timer) clearTimeout(timer)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** 主动对时:GET /health(无需登录)。用于首屏尚未发过任何业务请求就要判断时效的场景 */
|
|
130
|
+
async function fetchServerTime(ctx) {
|
|
131
|
+
const url = ctx.endpoint.replace(/\/+$/, '') + '/health'
|
|
132
|
+
const timeout = ctx.timeout || 15000
|
|
133
|
+
const t0 = Date.now()
|
|
134
|
+
const json = isMiniProgram() ? await getViaWx(url, timeout) : await getViaFetch(url, timeout)
|
|
135
|
+
const t1 = Date.now()
|
|
136
|
+
captureServerTime(ctx, json, t0, t1)
|
|
137
|
+
return ctx._timeOffset || 0
|
|
138
|
+
}
|
|
139
|
+
|
|
76
140
|
/** 单次原始请求(不含自动续期逻辑) */
|
|
77
141
|
async function rawRequest(ctx, path, body, token) {
|
|
78
142
|
const url = ctx.endpoint.replace(/\/+$/, '') + path
|
|
79
143
|
const headers = { 'Content-Type': 'application/json' }
|
|
80
144
|
if (token) headers.Authorization = 'Bearer ' + token
|
|
81
145
|
const timeout = ctx.timeout || 15000
|
|
146
|
+
const t0 = Date.now()
|
|
82
147
|
const { status, json } = isMiniProgram()
|
|
83
148
|
? await requestViaWx(url, encode(body), headers, timeout)
|
|
84
149
|
: await requestViaFetch(url, encode(body), headers, timeout)
|
|
150
|
+
captureServerTime(ctx, json, t0, Date.now())
|
|
85
151
|
if (!json || json.success !== true) {
|
|
86
152
|
throw new UdgRequestError(
|
|
87
153
|
json || { errorCode: 'HTTP_' + status, errorMessage: 'Gateway 返回异常(HTTP ' + status + ')' },
|
|
@@ -156,4 +222,4 @@ async function postAuthed(ctx, path, payload) {
|
|
|
156
222
|
}
|
|
157
223
|
}
|
|
158
224
|
|
|
159
|
-
module.exports = { post, postAuthed, rawPost, rawRequest, UdgRequestError }
|
|
225
|
+
module.exports = { post, postAuthed, rawPost, rawRequest, fetchServerTime, UdgRequestError }
|