bjchy-udg-sdk 1.4.4 → 1.5.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 CHANGED
@@ -99,7 +99,7 @@ const { status, token } = await client.checkScanLogin(sessionId)
99
99
  // ④ 外部体系已有 JWT(共用 JWT_SECRET,互通):init({ token }) 直入
100
100
  ```
101
101
 
102
- 辅助方法:`isLoggedIn()` / `getToken()` / `setToken(t)` / `logout()` / `getStreetKey()` / `jsapiSign(url?)`(公众号 JSSDK 签名,免登录)/ `buildScanQrContent(sessionId, opts?)` / `checkScanLogin(sessionId, opts?)`(单次校验,不轮询)/ `getScanSessionFromUrl(opts?)`(从 URL 读 sid,不发请求)/ `tryLoginFromUrl(opts?)`(组合入口,等价旧包 `checkUrlSessionAndLogin`)。
102
+ 辅助方法:`isLoggedIn()` / `getToken()` / `setToken(t)` / `logout()` / `getStreetKey()` / `client.wx.*`(小程序服务端 API,需 login)/ `jsapiSign(url?)`(公众号 JSSDK 签名,免登录)/ ...
103
103
 
104
104
  ### web-view 内 H5 的登录(传 code,不传 token)
105
105
 
@@ -124,6 +124,38 @@ await client.login({ code: new URLSearchParams(location.search).get('c') })
124
124
  - **refreshToken 也过期时**:H5 拿不到新 code,SDK 的自动重登会返回失败并抛鉴权错误(这是预期行为)。业务兜底:`wx.miniProgram.redirectTo` 回中转页重取 code。注意 `wx.miniProgram.postMessage` **不是实时的**(小程序只在分享/复制链接/后退/组件销毁时才收到),不能用它通知小程序。
125
125
  - **CORS**:H5 域名需在 Gateway 的跨域白名单里。
126
126
 
127
+ ### 小程序服务端能力(`client.wx.*`,需先 `login()`)
128
+
129
+ Gateway 代理三个常用微信服务端 API(凭据由租户关联的 `wxdb.miniprograms` 或 legacy `miniAppId/appSecret` 解析,详见 `docs/wechat-mini-integration.md`):
130
+
131
+ ```js
132
+ await client.login()
133
+
134
+ // 获取手机号(button open-type="getPhoneNumber" 的 code)
135
+ const phone = await client.wx.getPhoneNumber(code)
136
+ // → { phoneNumber, purePhoneNumber, countryCode }
137
+
138
+ // 生成小程序码(返回 JSON base64)
139
+ const { base64 } = await client.wx.getWxacode({ path: 'pages/share?id=1' })
140
+ // 不限制的小程序码(动态参数放 scene,适合大批量)
141
+ const { base64: qr2 } = await client.wx.getUnlimitedWxacode({
142
+ scene: 'id=1',
143
+ page: 'pages/share/index'
144
+ })
145
+
146
+ // 订阅消息(templateId 在管理后台小程序配置;栏位固定 thing2=content、thing4=hint)
147
+ await client.wx.sendSubscribeMessage({
148
+ content: '您的订单已发货',
149
+ hint: '点击查看详情',
150
+ page: 'pages/order/detail?id=1' // 可选
151
+ })
152
+ // 二维码/条码识别(imgUrl 公网可访问,或传 base64)
153
+ await client.wx.scanQrcode({ base64: imageBase64 })
154
+ // apiKey 登录批量通知时须传 touser
155
+ ```
156
+
157
+ 支持的登录方式:`wechat` / `scan` / `apikey`(公众号 `wechat-mp` 不可用)。
158
+
127
159
  ### 公众号 H5 的登录与 JSSDK
128
160
 
129
161
  微信公众号(服务号)里打开的 H5,用**网页授权**拿 openid,再用 code 换 UDG token。公众号凭据配在 Gateway 的 `.env`(全网关一份),**目标租户需在管理后台打开「公众号登录」开关**(默认关闭)。
@@ -271,9 +303,17 @@ await db.collection('users').doc(id).update({ data: { score: _.inc(10), tags: _.
271
303
  // 删除(filter 必须非空,防整表误删)
272
304
  await db.collection('users').where({ status: 9 }).remove() // → { stats: { removed } }
273
305
  await db.collection('users').doc(id).remove()
306
+
307
+ // set(upsert):有则更新、无则新增 → { _id, stats: { created, updated } }
308
+ await db.collection('users').doc('u10086').set({ data: { name: 'alice', status: 1 } })
309
+ await db.collection('users').set({ id: 'u10086', data: { name: 'alice' } })
310
+ // MySQL / Oracle 也可显式传主键列名(Gateway 自动查表主键校验)
311
+ await db.collection('users').set({ user_id: '10086', data: { name: 'alice' } })
274
312
  ```
275
313
 
276
- 用户登录(非 apiKey)时,Gateway 在 `add` 时自动写入 `_openid`(取自 token 的 `openId`,覆盖客户端传入值);`apiKey` 登录不注入,无需在 `data` 里手动传 `_openid`。
314
+ `set` 语义:MongoDB / CloudBase **整文档替换**(与微信云 `doc.set` 一致);MySQL / Oracle 按表**主键列** upsert(自动从数据字典读取主键,无需配置;复合主键表不支持)。`id` 参数即主键值,不必知道列名;也可传 `user_id` 等主键列名显式指定。
315
+
316
+ 用户登录(非 apiKey)时,Gateway 在 `add` / `set` 时自动写入 `_openid`(取自 token 的 `openId`,覆盖客户端传入值);`apiKey` 登录不注入,无需在 `data` 里手动传 `_openid`。
277
317
 
278
318
  ### 批量写入的事务保证(≤5000 条)
279
319
 
@@ -363,7 +403,7 @@ if (client.now() < new Date(activity.bookEnd)) { /* 可以报名 */ }
363
403
 
364
404
  ## 返回与错误
365
405
 
366
- 返回兼容微信云开发:`get → {data}`、`count → {total}`、`aggregate → {list}`、`add → {_id}/{ids}`、`update → {stats:{updated}}`、`remove → {stats:{removed}}`。
406
+ 返回兼容微信云开发:`get → {data}`、`count → {total}`、`aggregate → {list}`、`add → {_id}/{ids}`、`set → {_id, stats:{created,updated}}`、`update → {stats:{updated}}`、`remove → {stats:{removed}}`。
367
407
 
368
408
  失败抛统一错误对象:`{ 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` 引用的表)、`DUPLICATE_KEY`(409,唯一键冲突;批量写入时整批已回退,可修正数据后整批重发)、`FORBIDDEN`(Token 无效/过期,会自动 refresh 重试)、`TIMEOUT`)。
369
409
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bjchy-udg-sdk",
3
- "version": "1.4.4",
3
+ "version": "1.5.0",
4
4
  "description": "Universal Data Gateway SDK - 跨端统一数据访问(微信小程序 / Web / Node.js),API 兼容微信云开发",
5
5
  "main": "src/index.js",
6
6
  "type": "commonjs",
package/src/collection.js CHANGED
@@ -201,6 +201,27 @@ class DocumentReference {
201
201
  return { stats: { updated: data.updated || 0 }, errMsg: 'document.update:ok' }
202
202
  }
203
203
 
204
+ /**
205
+ * set({ data }) — 有则更新、无则新增(整文档替换,兼容微信云 doc.set)
206
+ */
207
+ async set(options) {
208
+ const payload = options && options.data
209
+ if (payload === undefined || payload === null) {
210
+ throw new Error('set 需要 data 字段')
211
+ }
212
+ const data = await post(this._ctx, '/api/set', {
213
+ collection: this._collection,
214
+ db: this._db,
215
+ id: this._id,
216
+ data: payload
217
+ })
218
+ return {
219
+ _id: data._id || this._id,
220
+ stats: data.stats || { created: 0, updated: 0 },
221
+ errMsg: 'document.set:ok'
222
+ }
223
+ }
224
+
204
225
  async remove() {
205
226
  const data = await post(this._ctx, '/api/delete', {
206
227
  collection: this._collection,
@@ -241,6 +262,36 @@ class Collection extends Query {
241
262
  }
242
263
  return { _id: ids[0], id: ids[0], errMsg: 'collection.add:ok' }
243
264
  }
265
+
266
+ /**
267
+ * set({ id, data }) 或 set({ [主键列名]: id值, data }) — upsert 单条
268
+ * 返回 { _id, stats: { created, updated } }
269
+ */
270
+ async set(options) {
271
+ if (!options || typeof options !== 'object') {
272
+ throw new Error('set 需要 options 对象')
273
+ }
274
+ const payload = options.data
275
+ if (payload === undefined || payload === null) {
276
+ throw new Error('set 需要 data 字段')
277
+ }
278
+ const body = {
279
+ collection: this._collection,
280
+ db: this._db,
281
+ data: payload
282
+ }
283
+ if (options.id !== undefined) body.id = options.id
284
+ const reserved = new Set(['data', 'id'])
285
+ for (const key of Object.keys(options)) {
286
+ if (!reserved.has(key)) body[key] = options[key]
287
+ }
288
+ const data = await post(this._ctx, '/api/set', body)
289
+ return {
290
+ _id: data._id,
291
+ stats: data.stats || { created: 0, updated: 0 },
292
+ errMsg: 'collection.set:ok'
293
+ }
294
+ }
244
295
  }
245
296
 
246
297
  module.exports = { Collection, Query, DocumentReference }
package/src/index.js CHANGED
@@ -24,6 +24,7 @@ const { command, UdgRegExp } = require('./command')
24
24
  const { rawPost, postAuthed, fetchServerTime, UdgRequestError } = require('./request')
25
25
  const { AuthManager } = require('./auth')
26
26
  const { AiNamespace } = require('./ai')
27
+ const { WxNamespace } = require('./wx')
27
28
  const storage = require('./storage')
28
29
 
29
30
  /**
@@ -111,6 +112,8 @@ class UdgClient {
111
112
  }
112
113
  // AI 能力(AI-4.1,可选模块):client.ai.complete / nlQuery / ask;租户需开通 aiEnabled
113
114
  this.ai = new AiNamespace(this._ctx)
115
+ // 微信小程序服务端 API:client.wx.*(需 login;见 docs/wechat-mini-integration.md)
116
+ this.wx = new WxNamespace(this._ctx)
114
117
  }
115
118
 
116
119
  /**
package/src/wx.js ADDED
@@ -0,0 +1,109 @@
1
+ /**
2
+ * SDK 小程序服务端能力封装(计划 §4.1)
3
+ *
4
+ * 三个方法均走 postAuthed —— 需先 client.login()(或 apiKey / scan 等有效 token)。
5
+ * Gateway 路径:/auth/wx/*
6
+ *
7
+ * 用法示例:
8
+ * await client.login()
9
+ * await client.wx.getPhoneNumber(code)
10
+ * await client.wx.getWxacode({ path: 'pages/share?id=1' })
11
+ * await client.wx.getUnlimitedWxacode({ scene: 'id=1', page: 'pages/share/index' })
12
+ * await client.wx.scanQrcode({ base64 }) // 或 { imgUrl: 'https://...' }
13
+ * await client.wx.sendSubscribeMessage({ content: '...', hint: '...' })
14
+ */
15
+ const { postAuthed } = require('./request')
16
+
17
+ class WxNamespace {
18
+ /**
19
+ * @param {object} ctx SDK 上下文(与 Database / AiNamespace 相同)
20
+ */
21
+ constructor(ctx) {
22
+ this._ctx = ctx
23
+ }
24
+
25
+ /**
26
+ * 获取手机号(button open-type="getPhoneNumber" 的 code)。
27
+ * @param {string} code
28
+ * @returns {Promise<{phoneNumber,purePhoneNumber,countryCode}>}
29
+ */
30
+ getPhoneNumber(code) {
31
+ if (!code) return Promise.reject(new Error('getPhoneNumber 需要 code 参数'))
32
+ return postAuthed(this._ctx, '/auth/wx/phone-number', { code })
33
+ }
34
+
35
+ /**
36
+ * 生成小程序码(Gateway 返回 JSON base64)。
37
+ * @param {object} opts { path, width?, envVersion?, isHyaline? }
38
+ * @returns {Promise<{contentType,base64,width}>}
39
+ */
40
+ getWxacode(opts) {
41
+ const o = opts || {}
42
+ if (!o.path) return Promise.reject(new Error('getWxacode 需要 path 参数'))
43
+ return postAuthed(this._ctx, '/auth/wx/wxacode', {
44
+ path: o.path,
45
+ width: o.width,
46
+ envVersion: o.envVersion,
47
+ isHyaline: o.isHyaline
48
+ })
49
+ }
50
+
51
+ /**
52
+ * 生成不限制的小程序码(scene + 可选 page,数量不限)。
53
+ * 动态参数放 scene;page 不能带 query。小程序 onLoad 用 decodeURIComponent(query.scene) 取值。
54
+ * @param {object} opts { scene, page?, checkPath?, width?, envVersion?, isHyaline? }
55
+ * @returns {Promise<{contentType,base64,width}>}
56
+ */
57
+ getUnlimitedWxacode(opts) {
58
+ const o = opts || {}
59
+ if (!o.scene) return Promise.reject(new Error('getUnlimitedWxacode 需要 scene 参数'))
60
+ return postAuthed(this._ctx, '/auth/wx/wxacode-unlimited', {
61
+ scene: o.scene,
62
+ page: o.page,
63
+ checkPath: o.checkPath,
64
+ width: o.width,
65
+ envVersion: o.envVersion,
66
+ isHyaline: o.isHyaline,
67
+ autoColor: o.autoColor,
68
+ lineColor: o.lineColor
69
+ })
70
+ }
71
+
72
+ /**
73
+ * 二维码/条码识别(微信 imgQrcode)。imgUrl 与 base64 二选一;上传图片 ≤2MB。
74
+ * @param {object} opts { imgUrl?, base64?, filename? }
75
+ * @returns {Promise<{codeResults: Array<{typeName,data,pos}>, imgSize?: {w,h}}>}
76
+ */
77
+ scanQrcode(opts) {
78
+ const o = opts || {}
79
+ if (!o.imgUrl && !o.base64) {
80
+ return Promise.reject(new Error('scanQrcode 需要 imgUrl 或 base64 参数'))
81
+ }
82
+ return postAuthed(this._ctx, '/auth/wx/scan-qrcode', {
83
+ imgUrl: o.imgUrl,
84
+ base64: o.base64,
85
+ filename: o.filename
86
+ })
87
+ }
88
+
89
+ /**
90
+ * 发送订阅消息。templateId 由网关读注册表;SDK 只传 content(thing2)与 hint(thing4)。
91
+ * @param {object} opts { touser?, page?, content, hint, miniprogramState? }
92
+ * touser — apiKey 登录必填;JWT 可省略(默认当前 openId)
93
+ */
94
+ sendSubscribeMessage(opts) {
95
+ const o = opts || {}
96
+ if (!o.content || !o.hint) {
97
+ return Promise.reject(new Error('sendSubscribeMessage 需要 content 与 hint'))
98
+ }
99
+ return postAuthed(this._ctx, '/auth/wx/subscribe-message', {
100
+ touser: o.touser,
101
+ page: o.page,
102
+ content: o.content,
103
+ hint: o.hint,
104
+ miniprogramState: o.miniprogramState
105
+ })
106
+ }
107
+ }
108
+
109
+ module.exports = { WxNamespace }