bjchy-udg-sdk 1.0.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 ADDED
@@ -0,0 +1,176 @@
1
+ # UDG SDK
2
+
3
+ 跨端统一数据访问 SDK(微信小程序 / Web / Node.js ≥18),API 兼容微信云开发 `wx.cloud.database()`,连接 UDG Gateway 访问 CloudBase 或 MongoDB 业务库。零运行时依赖。
4
+
5
+ ## 安装 / 引入
6
+
7
+ | 环境 | 方式 |
8
+ |------|------|
9
+ | Node.js | `npm install <本包>` 或 `require('../sdk/src/index.js')`;内部使用全局 `fetch`(Node ≥18) |
10
+ | Web(Vue/React) | 经 bundler 直接 `import udg from 'udg-sdk'`;内部使用 `fetch` |
11
+ | 微信小程序 | 推荐 npm 安装(见下);内部自动使用 `wx.request`(需在小程序后台将 Gateway 域名加入 request 合法域名) |
12
+
13
+ 环境自动识别,三端 API 完全一致。
14
+
15
+ ### 微信小程序:用 npm 安装并保持最新
16
+
17
+ `sdk/` 目录改动推送到 master 时(见仓库根 `.githooks/pre-push` + `scripts/publish-sdk.sh`),会自动 `git subtree split` 同步到独立分支 `sdk-dist`——该分支根目录就是完整的 `udg-sdk` npm 包,可以直接被小程序项目安装:
18
+
19
+ ```json
20
+ // 小程序项目 package.json
21
+ {
22
+ "dependencies": {
23
+ "udg-sdk": "git+https://git.weixin.qq.com/wangzhongsheng/UDGV1.git#sdk-dist"
24
+ }
25
+ }
26
+ ```
27
+
28
+ ```bash
29
+ npm install
30
+ # 再在微信开发者工具里「工具 → 构建 npm」
31
+ ```
32
+
33
+ 之后每次要拿最新版本:
34
+
35
+ ```bash
36
+ npm update udg-sdk
37
+ # 重新「工具 → 构建 npm」
38
+ ```
39
+
40
+ ⚠️ `npm install` / `npm update` 只刷新 `node_modules`,小程序实际运行用的是 `miniprogram_npm` 目录——每次装完/更新完**都要重新点一次「工具 → 构建 npm」**,否则代码不生效,容易误以为是 SDK 的 bug。
41
+
42
+ 新克隆本仓库、要参与 SDK 开发的机器,需执行一次 `scripts/setup-hooks.sh` 激活 `.githooks/`(否则 `sdk/` 的改动推送后不会自动同步到 `sdk-dist`)。
43
+
44
+ 不建议再手工把 `sdk/src` 拷贝进小程序项目——容易漏更新导致新旧字段不一致(例如曾经的登录返回字段从 `openid` 改名为 `openId`,手工拷贝的旧副本没跟上,导致小程序端读到 `undefined`)。
45
+
46
+ ## 初始化与登录
47
+
48
+ ```js
49
+ const udg = require('udg-sdk')
50
+
51
+ const client = udg.init({
52
+ endpoint: 'https://udg.example.com', // 必填:Gateway 地址(生产必须 HTTPS)
53
+ appid: 'wx1234567890abcdef', // appid / streetKey 二选一:小程序 AppID(租户标识)
54
+ defaultDb: 'main', // 可选:覆盖管理后台为该 appid 配置的 defaultDb(database() 不传参时使用)
55
+ token: '<JWT>', // 可选:外部已有 token 直入
56
+ timeout: 15000 // 可选,默认 15s
57
+ })
58
+ ```
59
+
60
+ **Web 多租户场景**:一套前端产物按 URL 路径区分租户(如 `/w/hjl`),无需硬编码 `appid`:
61
+
62
+ ```js
63
+ const streetKey = location.pathname.split('/').pop() // 从当前 URL 解析出 'hjl'
64
+ const client = udg.init({ endpoint, streetKey })
65
+ // 首次 login() / pollScanLogin() 时才会调用 POST /tenant/resolve 解析出 appid(结果本地缓存,同 streetKey 不重复请求)
66
+ // 同时传 appid 与 streetKey 时以 appid 为准,忽略 streetKey,不会调用 resolve
67
+ ```
68
+
69
+ **登录(四选一)**,token 缓存 / 自动续期 / 自动重登由 SDK 内部处理:
70
+
71
+ ```js
72
+ // ① 小程序:自动 wx.login(需在管理后台为该 appid 配置微信 AppSecret)
73
+ const { token, openId } = await client.login() // openId 同时写入 JWT;非小程序环境无 openId
74
+
75
+ // ② Node / 脚本:apiKey 登录(apiKey 按 appid 在管理后台配置,放环境变量)
76
+ await client.login({ apiKey: process.env.UDG_API_KEY })
77
+
78
+ // ③ Web 扫码登录(协议兼容 MGAPIV3:log 集合 + scancode/scanned/confirmed 状态机)
79
+ const { sessionId } = client.createScanSession()
80
+ renderQrCode(client.buildScanQrContent(sessionId)) // 二维码内容,业务渲染成图片
81
+ const { userInfo } = await client.pollScanLogin(sessionId) // 确认后自动保存 token
82
+ // 小程序确认端:await client.approveScanLogin({ id, admininfo })(需先 login())
83
+
84
+ // ④ 外部体系已有 JWT(共用 JWT_SECRET,互通):init({ token }) 直入
85
+ ```
86
+
87
+ 辅助方法:`isLoggedIn()` / `getToken()` / `setToken(t)` / `logout()` / `getStreetKey()` / `buildScanQrContent(sessionId, opts?)`。
88
+
89
+ **openId 约定**:JWT 内统一字段名为 `openId`(小程序 `wx.login`、网页扫码、外部 MGAPIV3 token 均如此)。小程序 `login()` 成功时响应含 `openId`;扫码登录的 `openId` 在 JWT 中,业务侧一般从 `userInfo` 或解码 token 读取。
90
+
91
+ envId / mongoDatabase / AppSecret 由服务端从 `wxdb.config` 读取,客户端不传、不可传。
92
+
93
+ **同一 appid 多数据源**(一个 client、一份 token,用 `dbKey` 切换;管理后台按 `databases[]` 登记,详见 `docs/multi-database-dbkey.md`):
94
+
95
+ ```js
96
+ const client = udg.init({ endpoint, appid })
97
+ await client.login()
98
+
99
+ const cloudDb = client.database() // 不传 → 用租户 defaultDb
100
+ const mongoDb = client.database('mongo') // 显式 dbKey
101
+ const mapsDb = client.database('maps') // 多租户共享的只读公共库(access: readonly)
102
+ ```
103
+
104
+ ## 查询
105
+
106
+ ```js
107
+ const _ = db.command
108
+
109
+ // 链式查询(与 wx.cloud 一致)
110
+ const { data } = await db.collection('users')
111
+ .where({ status: 1, age: _.gte(18).and(_.lt(60)) })
112
+ .field({ name: true, age: true })
113
+ .orderBy('age', 'desc')
114
+ .skip(20)
115
+ .limit(20)
116
+ .get()
117
+
118
+ // 计数
119
+ const { total } = await db.collection('users').where({ status: 1 }).count()
120
+
121
+ // 正则(两种写法均可)
122
+ db.collection('users').where({ name: new db.RegExp({ regexp: '^陈', options: 'i' }) }).get()
123
+ db.collection('users').where({ name: /^陈/i }).get()
124
+
125
+ // 按 _id
126
+ const { data: [doc] } = await db.collection('users').doc(id).get()
127
+ ```
128
+
129
+ 支持的查询指令:`eq neq gt gte lt lte in nin exists size all elemMatch mod and or nor not`;也可直接写 MongoDB 风格 filter(如 `{ age: { $gte: 18 } }`)。不支持的运算符 Gateway 直接报错。
130
+
131
+ ## 写入
132
+
133
+ ```js
134
+ // 单条 → { _id }
135
+ const { _id } = await db.collection('users').add({ data: { name: 'alice', createdAt: new Date() } })
136
+
137
+ // 批量(≤100 条)→ { ids }
138
+ const { ids } = await db.collection('users').add({ data: [{...}, {...}] })
139
+
140
+ // 更新(where 匹配全部;doc(id) 单条)
141
+ await db.collection('users').where({ status: 0 }).update({ data: { status: 1 } })
142
+ await db.collection('users').doc(id).update({ data: { score: _.inc(10), tags: _.push(['new']) } })
143
+
144
+ // 删除(filter 必须非空,防整表误删)
145
+ await db.collection('users').where({ status: 9 }).remove() // → { stats: { removed } }
146
+ await db.collection('users').doc(id).remove()
147
+ ```
148
+
149
+ 用户登录(非 apiKey)时,Gateway 在 `add` 时自动写入 `_openid`(取自 token 的 `openId`,覆盖客户端传入值);`apiKey` 登录不注入,无需在 `data` 里手动传 `_openid`。
150
+
151
+ 更新指令:`set remove inc mul push pop shift unshift addToSet pull pullAll`;也可传原生 update 文档(顶层全 `$` 键时直传,如 `{ $set: {...}, $inc: {...} }`)。
152
+
153
+ ## 聚合(重点能力)
154
+
155
+ ```js
156
+ const { list } = await db.collection('orders').aggregate()
157
+ .match({ year: 2026, status: 'paid' })
158
+ .group({ _id: '$type', total: { $sum: '$amount' }, n: { $sum: 1 } })
159
+ .sort({ total: -1 })
160
+ .limit(10)
161
+ .end()
162
+ ```
163
+
164
+ 支持 stage:`match group project sort limit skip count lookup unwind addFields replaceRoot sample sortByCount`。stage 内表达式使用 MongoDB 原生写法(`$sum` / `$cond` / `$dateToString` …),两个数据源写法一致。
165
+
166
+ ## 返回与错误
167
+
168
+ 返回兼容微信云开发:`get → {data}`、`count → {total}`、`aggregate → {list}`、`add → {_id}/{ids}`、`update → {stats:{updated}}`、`remove → {stats:{removed}}`。
169
+
170
+ 失败抛统一错误对象:`{ errorCode, errorMessage, requestId, timestamp }`(如 `UNSUPPORTED_OPERATOR`、`TENANT_NOT_FOUND`、`DB_NOT_FOUND`(dbKey 未在 databases[] 中登记)、`READONLY_DATABASE`(对只读 dbKey 执行了写操作)、`FORBIDDEN`(Token 无效/过期,会自动 refresh 重试)、`TIMEOUT`)。
171
+
172
+ ## 说明
173
+
174
+ - 日期:SDK 与 Gateway 以 `{ $date: 毫秒 }` 传输,业务代码直接用 `Date` 对象读写即可
175
+ - `db.serverDate()` V1 以客户端时间近似
176
+ - distinct / 文件上传 / 实时订阅:V1 不提供
package/package.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "bjchy-udg-sdk",
3
+ "version": "1.0.0",
4
+ "description": "Universal Data Gateway SDK - 跨端统一数据访问(微信小程序 / Web / Node.js),API 兼容微信云开发",
5
+ "main": "src/index.js",
6
+ "type": "commonjs",
7
+ "engines": {
8
+ "node": ">=18"
9
+ },
10
+ "files": [
11
+ "src",
12
+ "README.md"
13
+ ],
14
+ "keywords": ["udg", "cloudbase", "mongodb", "wx.cloud", "database"],
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://git.weixin.qq.com/wangzhongsheng/UDGV1.git",
19
+ "directory": "sdk"
20
+ },
21
+ "dependencies": {}
22
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * 聚合链式 API(兼容微信云开发 aggregate):
3
+ * coll.aggregate().match({...}).group({...}).sort({...}).limit(10).end()
4
+ * 内部转换为 MongoDB 风格 pipeline 提交 Gateway。
5
+ */
6
+ const { post } = require('./request')
7
+
8
+ class Aggregate {
9
+ constructor(ctx, collectionName, db) {
10
+ this._ctx = ctx
11
+ this._collection = collectionName
12
+ this._db = db || ''
13
+ this._pipeline = []
14
+ }
15
+
16
+ _push(stage, spec) {
17
+ this._pipeline.push({ [stage]: spec })
18
+ return this
19
+ }
20
+
21
+ match(spec) { return this._push('$match', spec) }
22
+ group(spec) { return this._push('$group', spec) }
23
+ project(spec) { return this._push('$project', spec) }
24
+ sort(spec) { return this._push('$sort', spec) }
25
+ limit(n) { return this._push('$limit', n) }
26
+ skip(n) { return this._push('$skip', n) }
27
+ count(fieldName) { return this._push('$count', fieldName) }
28
+ lookup(spec) { return this._push('$lookup', spec) }
29
+ unwind(spec) { return this._push('$unwind', spec) }
30
+ addFields(spec) { return this._push('$addFields', spec) }
31
+ replaceRoot(spec) { return this._push('$replaceRoot', spec) }
32
+ sample(spec) { return this._push('$sample', typeof spec === 'number' ? { size: spec } : spec) }
33
+ sortByCount(spec) { return this._push('$sortByCount', spec) }
34
+
35
+ async end() {
36
+ const data = await post(this._ctx, '/api/query', {
37
+ collection: this._collection,
38
+ db: this._db,
39
+ aggregate: this._pipeline
40
+ })
41
+ return { list: data.list || [], errMsg: 'collection.aggregate:ok' }
42
+ }
43
+ }
44
+
45
+ module.exports = { Aggregate }
package/src/auth.js ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * AuthManager:token 全生命周期管理(SDK 内部,业务无感)。
3
+ * - 登录:wx.login(小程序)/ apiKey(Node/Web/脚本)/ 扫码 / 外部 token 直入
4
+ * - 持久化缓存:未过期不重复登录
5
+ * - 自动续期:请求 403 时用 refreshToken 换新并重试(见 request.js)
6
+ * - 自动重登:refresh 失效且为微信登录模式时,自动重新 wx.login
7
+ */
8
+ const storage = require('./storage')
9
+
10
+ /* ---- 无依赖 base64url 解码(小程序无 Buffer/atob) ---- */
11
+ const B64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
12
+ function b64Decode(input) {
13
+ let str = input.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '')
14
+ let out = ''
15
+ let bits = 0
16
+ let value = 0
17
+ for (let i = 0; i < str.length; i++) {
18
+ const idx = B64_CHARS.indexOf(str[i])
19
+ if (idx === -1) continue
20
+ value = (value << 6) | idx
21
+ bits += 6
22
+ if (bits >= 8) {
23
+ bits -= 8
24
+ out += String.fromCharCode((value >> bits) & 0xff)
25
+ }
26
+ }
27
+ return out
28
+ }
29
+
30
+ /** 解析 JWT payload(不校验签名,仅用于读 exp 等) */
31
+ function decodeJwtPayload(token) {
32
+ try {
33
+ const part = String(token).split('.')[1]
34
+ if (!part) return null
35
+ let json
36
+ if (typeof Buffer !== 'undefined') {
37
+ json = Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')
38
+ } else {
39
+ // eslint-disable-next-line no-undef
40
+ json = decodeURIComponent(escape(b64Decode(part)))
41
+ }
42
+ return JSON.parse(json)
43
+ } catch (e) {
44
+ return null
45
+ }
46
+ }
47
+
48
+ function isMiniProgram() {
49
+ // eslint-disable-next-line no-undef
50
+ return typeof wx !== 'undefined' && wx !== null && typeof wx.login === 'function'
51
+ }
52
+
53
+ function wxLoginCode() {
54
+ return new Promise((resolve, reject) => {
55
+ // eslint-disable-next-line no-undef
56
+ wx.login({
57
+ success: (res) => (res.code ? resolve(res.code) : reject(new Error('wx.login 未返回 code'))),
58
+ fail: (err) => reject(new Error(err.errMsg || 'wx.login 失败'))
59
+ })
60
+ })
61
+ }
62
+
63
+ class AuthManager {
64
+ /**
65
+ * @param {object} ctx SDK 上下文 { endpoint, appid, ... }
66
+ * @param {function} rawPost 无鉴权请求函数 (path, body) => Promise<data>
67
+ */
68
+ constructor(ctx, rawPost) {
69
+ this.ctx = ctx
70
+ this.rawPost = rawPost
71
+ this.token = ''
72
+ this.refreshToken = ''
73
+ this.mode = '' // 'wechat' | 'apikey' | 'scan' | 'external'
74
+ this._apiKey = '' // apiKey 模式下留存,供自动重登
75
+ this._bindStorageKey()
76
+ this._load()
77
+ }
78
+
79
+ _bindStorageKey() {
80
+ this.storageKey = 'udg_auth_' + (this.ctx.appid || '') + '@' + this.ctx.endpoint.replace(/^https?:\/\//, '').replace(/\/+$/, '')
81
+ }
82
+
83
+ /** init 仅传 streetKey 时,appid 需异步 resolve;resolve 完成后重新计算存储键并加载该 appid 下已缓存的 token */
84
+ rebindAppid() {
85
+ this._bindStorageKey()
86
+ this._load()
87
+ }
88
+
89
+ _load() {
90
+ const saved = storage.get(this.storageKey)
91
+ if (saved && saved.token) {
92
+ this.token = saved.token
93
+ this.refreshToken = saved.refreshToken || ''
94
+ this.mode = saved.mode || ''
95
+ }
96
+ }
97
+
98
+ _save() {
99
+ storage.set(this.storageKey, {
100
+ token: this.token,
101
+ refreshToken: this.refreshToken,
102
+ mode: this.mode
103
+ })
104
+ }
105
+
106
+ /** token 是否仍有效(预留 60s 余量) */
107
+ isTokenValid() {
108
+ if (!this.token) return false
109
+ const payload = decodeJwtPayload(this.token)
110
+ if (!payload || !payload.exp) return false
111
+ return payload.exp * 1000 > Date.now() + 60 * 1000
112
+ }
113
+
114
+ setTokens(token, refreshToken, mode) {
115
+ this.token = token || ''
116
+ if (refreshToken !== undefined) this.refreshToken = refreshToken || ''
117
+ if (mode) this.mode = mode
118
+ this._save()
119
+ }
120
+
121
+ /** 外部 token 直入(init({token}) / setToken) */
122
+ setExternalToken(token) {
123
+ this.token = token || ''
124
+ this.mode = 'external'
125
+ // 外部 token 不写持久化(由外部体系管理生命周期),也不参与自动续期
126
+ }
127
+
128
+ logout() {
129
+ this.token = ''
130
+ this.refreshToken = ''
131
+ this.mode = ''
132
+ this._apiKey = ''
133
+ storage.remove(this.storageKey)
134
+ }
135
+
136
+ /**
137
+ * 登录(幂等:缓存 token 未过期时直接复用,force 可强制重登)。
138
+ * - login():小程序环境自动 wx.login
139
+ * - login({ apiKey }):密钥登录
140
+ */
141
+ async login(opts) {
142
+ const o = opts || {}
143
+ if (o.apiKey) this._apiKey = o.apiKey
144
+ if (!o.force && this.isTokenValid()) {
145
+ const payload = decodeJwtPayload(this.token)
146
+ return { token: this.token, openId: payload && payload.openId, cached: true }
147
+ }
148
+ if (this._apiKey) {
149
+ const data = await this.rawPost('/auth/login', { appid: this.ctx.appid, apiKey: this._apiKey })
150
+ this.setTokens(data.token, data.refreshToken, 'apikey')
151
+ return { token: this.token, cached: false }
152
+ }
153
+ if (isMiniProgram()) {
154
+ const code = await wxLoginCode()
155
+ const data = await this.rawPost('/auth/wxlogin', { appid: this.ctx.appid, code })
156
+ this.openId = data.openId
157
+ this.setTokens(data.token, data.refreshToken, 'wechat')
158
+ return { token: this.token, openId: data.openId, cached: false }
159
+ }
160
+ throw new Error('login 需要 apiKey 参数(非小程序环境),或在微信小程序环境中自动使用 wx.login')
161
+ }
162
+
163
+ /** 用 refreshToken 续期;成功返回 true */
164
+ async refresh() {
165
+ if (!this.refreshToken) return false
166
+ try {
167
+ const data = await this.rawPost('/auth/refresh', { refreshToken: this.refreshToken })
168
+ this.setTokens(data.token, data.refreshToken)
169
+ return true
170
+ } catch (e) {
171
+ return false
172
+ }
173
+ }
174
+
175
+ /** 续期失败后的自动重登(仅微信 / apiKey 模式可行) */
176
+ async relogin() {
177
+ if (this.mode === 'wechat' && isMiniProgram()) {
178
+ await this.login({ force: true })
179
+ return true
180
+ }
181
+ if (this.mode === 'apikey' && this._apiKey) {
182
+ await this.login({ apiKey: this._apiKey, force: true })
183
+ return true
184
+ }
185
+ return false
186
+ }
187
+ }
188
+
189
+ module.exports = { AuthManager, decodeJwtPayload, isMiniProgram }
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Collection / Query / DocumentReference:兼容微信云开发链式 API。
3
+ * coll.where({...}).field({...}).orderBy('age','desc').skip(0).limit(20).get()
4
+ * coll.where({...}).count()
5
+ * coll.add({ data })
6
+ * coll.doc(id).get() / .update({ data }) / .remove()
7
+ * coll.where({...}).update({ data }) / .remove()
8
+ */
9
+ const { post } = require('./request')
10
+ const { Aggregate } = require('./aggregate')
11
+ const { UPDATE_OP_KEYS } = require('./command')
12
+ const { isPlainObject } = require('./serialize')
13
+
14
+ /** 原生 JS RegExp → { $regex, $options }(兼容 wx.cloud 中直接写正则的用法) */
15
+ function normalizeFilter(value) {
16
+ if (value instanceof RegExp) {
17
+ return { $regex: value.source, $options: value.flags || '' }
18
+ }
19
+ if (Array.isArray(value)) return value.map(normalizeFilter)
20
+ if (isPlainObject(value)) {
21
+ const out = {}
22
+ for (const k of Object.keys(value)) out[k] = normalizeFilter(value[k])
23
+ return out
24
+ }
25
+ return value
26
+ }
27
+
28
+ /** wx 风格 update data → MongoDB 风格 update 文档 */
29
+ function buildUpdateDoc(data) {
30
+ if (!isPlainObject(data) || Object.keys(data).length === 0) {
31
+ throw new Error('update 需要非空的 data 对象')
32
+ }
33
+ const keys = Object.keys(data)
34
+ // 原始 MongoDB update 文档直传(高级用法)
35
+ if (keys.every((k) => k.startsWith('$'))) return data
36
+
37
+ const update = {}
38
+ const put = (op, field, value) => {
39
+ if (!update[op]) update[op] = {}
40
+ update[op][field] = value
41
+ }
42
+ for (const field of keys) {
43
+ const v = data[field]
44
+ if (isPlainObject(v)) {
45
+ const vKeys = Object.keys(v)
46
+ const opKey = vKeys.length >= 1 && UPDATE_OP_KEYS.has(vKeys[0]) ? vKeys[0] : null
47
+ if (opKey && vKeys.length === 1) {
48
+ if (opKey === '$unset') {
49
+ put('$unset', field, '')
50
+ } else {
51
+ put(opKey, field, v[opKey])
52
+ }
53
+ continue
54
+ }
55
+ }
56
+ put('$set', field, v)
57
+ }
58
+ return update
59
+ }
60
+
61
+ class Query {
62
+ constructor(ctx, collectionName, db, state) {
63
+ this._ctx = ctx
64
+ this._collection = collectionName
65
+ this._db = db || ''
66
+ this._state = state || {}
67
+ }
68
+
69
+ _clone(patch) {
70
+ return new Query(this._ctx, this._collection, this._db, Object.assign({}, this._state, patch))
71
+ }
72
+
73
+ where(filter) {
74
+ return this._clone({ filter: normalizeFilter(filter || {}) })
75
+ }
76
+
77
+ field(projection) {
78
+ return this._clone({ projection })
79
+ }
80
+
81
+ orderBy(fieldName, direction) {
82
+ const sort = Object.assign({}, this._state.sort)
83
+ sort[fieldName] = direction === 'desc' || direction === -1 ? -1 : 1
84
+ return this._clone({ sort })
85
+ }
86
+
87
+ limit(n) {
88
+ return this._clone({ limit: n })
89
+ }
90
+
91
+ skip(n) {
92
+ return this._clone({ skip: n })
93
+ }
94
+
95
+ async get() {
96
+ const data = await post(this._ctx, '/api/query', {
97
+ collection: this._collection,
98
+ db: this._db,
99
+ filter: this._state.filter || {},
100
+ projection: this._state.projection,
101
+ sort: this._state.sort,
102
+ limit: this._state.limit,
103
+ skip: this._state.skip
104
+ })
105
+ return { data: data.data || [], errMsg: 'collection.get:ok' }
106
+ }
107
+
108
+ async count() {
109
+ const data = await post(this._ctx, '/api/query', {
110
+ collection: this._collection,
111
+ db: this._db,
112
+ filter: this._state.filter || {},
113
+ count: true
114
+ })
115
+ return { total: data.total || 0, errMsg: 'collection.count:ok' }
116
+ }
117
+
118
+ async update(options) {
119
+ const data = await post(this._ctx, '/api/update', {
120
+ collection: this._collection,
121
+ db: this._db,
122
+ filter: this._state.filter || {},
123
+ update: buildUpdateDoc(options && options.data),
124
+ multi: true
125
+ })
126
+ return { stats: { updated: data.updated || 0 }, errMsg: 'collection.update:ok' }
127
+ }
128
+
129
+ async remove() {
130
+ const data = await post(this._ctx, '/api/delete', {
131
+ collection: this._collection,
132
+ db: this._db,
133
+ filter: this._state.filter || {},
134
+ multi: true
135
+ })
136
+ return { stats: { removed: data.removed || 0 }, errMsg: 'collection.remove:ok' }
137
+ }
138
+ }
139
+
140
+ class DocumentReference {
141
+ constructor(ctx, collectionName, db, id) {
142
+ this._ctx = ctx
143
+ this._collection = collectionName
144
+ this._db = db || ''
145
+ this._id = id
146
+ }
147
+
148
+ async get() {
149
+ const data = await post(this._ctx, '/api/query', {
150
+ collection: this._collection,
151
+ db: this._db,
152
+ filter: { _id: this._id },
153
+ limit: 1
154
+ })
155
+ return { data: data.data || [], errMsg: 'document.get:ok' }
156
+ }
157
+
158
+ async update(options) {
159
+ const data = await post(this._ctx, '/api/update', {
160
+ collection: this._collection,
161
+ db: this._db,
162
+ filter: { _id: this._id },
163
+ update: buildUpdateDoc(options && options.data),
164
+ multi: false
165
+ })
166
+ return { stats: { updated: data.updated || 0 }, errMsg: 'document.update:ok' }
167
+ }
168
+
169
+ async remove() {
170
+ const data = await post(this._ctx, '/api/delete', {
171
+ collection: this._collection,
172
+ db: this._db,
173
+ filter: { _id: this._id },
174
+ multi: false
175
+ })
176
+ return { stats: { removed: data.removed || 0 }, errMsg: 'document.remove:ok' }
177
+ }
178
+ }
179
+
180
+ class Collection extends Query {
181
+ doc(id) {
182
+ return new DocumentReference(this._ctx, this._collection, this._db, id)
183
+ }
184
+
185
+ aggregate() {
186
+ return new Aggregate(this._ctx, this._collection, this._db)
187
+ }
188
+
189
+ /**
190
+ * add({ data: {...} }) 单条 → { _id, id }
191
+ * add({ data: [...] }) 批量 → { ids }
192
+ */
193
+ async add(options) {
194
+ const payload = options && options.data
195
+ if (payload === undefined || payload === null) {
196
+ throw new Error('add 需要 data 字段')
197
+ }
198
+ const data = await post(this._ctx, '/api/create', {
199
+ collection: this._collection,
200
+ db: this._db,
201
+ data: payload
202
+ })
203
+ const ids = data.ids || []
204
+ if (Array.isArray(payload)) {
205
+ return { ids, errMsg: 'collection.add:ok' }
206
+ }
207
+ return { _id: ids[0], id: ids[0], errMsg: 'collection.add:ok' }
208
+ }
209
+ }
210
+
211
+ module.exports = { Collection, Query, DocumentReference }
package/src/command.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * db.command:兼容微信云开发的查询/更新指令,序列化为 MongoDB 风格运算符。
3
+ *
4
+ * 查询指令返回的对象可 JSON 直传,如 _.gt(1) → { $gt: 1 };
5
+ * 支持 .and() 链式合并同字段条件:_.gt(1).and(_.lt(5)) → { $gt: 1, $lt: 5 }。
6
+ */
7
+
8
+ function queryCmd(obj) {
9
+ Object.defineProperty(obj, 'and', {
10
+ enumerable: false,
11
+ value: function (other) {
12
+ return queryCmd(Object.assign({}, this, other))
13
+ }
14
+ })
15
+ return obj
16
+ }
17
+
18
+ const command = {
19
+ // 比较
20
+ eq: (v) => queryCmd({ $eq: v }),
21
+ neq: (v) => queryCmd({ $ne: v }),
22
+ ne: (v) => queryCmd({ $ne: v }),
23
+ gt: (v) => queryCmd({ $gt: v }),
24
+ gte: (v) => queryCmd({ $gte: v }),
25
+ lt: (v) => queryCmd({ $lt: v }),
26
+ lte: (v) => queryCmd({ $lte: v }),
27
+ in: (v) => queryCmd({ $in: v }),
28
+ nin: (v) => queryCmd({ $nin: v }),
29
+ // 元素 / 数组
30
+ exists: (v) => queryCmd({ $exists: Boolean(v) }),
31
+ size: (v) => queryCmd({ $size: v }),
32
+ all: (v) => queryCmd({ $all: v }),
33
+ elemMatch: (v) => queryCmd({ $elemMatch: v }),
34
+ mod: (divisor, remainder) => queryCmd({ $mod: [divisor, remainder] }),
35
+ // 逻辑(顶层用法:_.or([{...},{...}]))
36
+ and: (list) => ({ $and: list }),
37
+ or: (list) => ({ $or: list }),
38
+ nor: (list) => ({ $nor: list }),
39
+ not: (cond) => queryCmd({ $not: cond }),
40
+
41
+ // ===== 更新指令(字段级) =====
42
+ set: (v) => ({ $set: v }),
43
+ remove: () => ({ $unset: true }),
44
+ inc: (v) => ({ $inc: v }),
45
+ mul: (v) => ({ $mul: v }),
46
+ push: (v) => ({ $push: Array.isArray(v) ? { $each: v } : v }),
47
+ pop: () => ({ $pop: 1 }),
48
+ shift: () => ({ $pop: -1 }),
49
+ unshift: (v) => ({ $push: { $each: Array.isArray(v) ? v : [v], $position: 0 } }),
50
+ addToSet: (v) => ({ $addToSet: v }),
51
+ pull: (v) => ({ $pull: v }),
52
+ pullAll: (v) => ({ $pullAll: v })
53
+ }
54
+
55
+ /** 更新指令的序列化形态(collection.update 用于识别字段级更新指令) */
56
+ const UPDATE_OP_KEYS = new Set([
57
+ '$set', '$unset', '$inc', '$mul', '$push', '$pop', '$pull', '$pullAll', '$addToSet',
58
+ '$rename', '$min', '$max', '$currentDate'
59
+ ])
60
+
61
+ /** RegExp 构造:new db.RegExp({ regexp, options }) → { $regex, $options } */
62
+ function UdgRegExp(opts) {
63
+ const o = opts || {}
64
+ return { $regex: o.regexp || '', $options: o.options || '' }
65
+ }
66
+
67
+ module.exports = { command, UPDATE_OP_KEYS, UdgRegExp }
@@ -0,0 +1,29 @@
1
+ const { Collection } = require('./collection')
2
+ const { command, UdgRegExp } = require('./command')
3
+
4
+ class Database {
5
+ /**
6
+ * @param {object} ctx SDK 上下文
7
+ * @param {string} [dbKey] 目标数据源别名;不传则由 Gateway 用租户 defaultDb
8
+ */
9
+ constructor(ctx, dbKey) {
10
+ this._ctx = ctx
11
+ this._db = dbKey || ''
12
+ this.command = command
13
+ this.RegExp = UdgRegExp
14
+ }
15
+
16
+ collection(name) {
17
+ if (!name || typeof name !== 'string') {
18
+ throw new Error('collection 名称必须是非空字符串')
19
+ }
20
+ return new Collection(this._ctx, name, this._db)
21
+ }
22
+
23
+ serverDate() {
24
+ // V1 简化:以客户端时间近似(真正的服务端时间可后续在 Gateway 支持)
25
+ return new Date()
26
+ }
27
+ }
28
+
29
+ module.exports = { Database }
package/src/index.js ADDED
@@ -0,0 +1,217 @@
1
+ /**
2
+ * UDG SDK 入口。
3
+ *
4
+ * const udg = require('udg-sdk')
5
+ * const client = udg.init({ endpoint, appid, defaultDb?: 'main' })
6
+ * // defaultDb 可覆盖管理后台为该 appid 配置的 defaultDb;client.database() 不传参时使用
7
+ * // Web 多租户场景可只传 streetKey(appid 与 streetKey 二选一,同传以 appid 为准):
8
+ * // udg.init({ endpoint, streetKey: 'hjl' })
9
+ *
10
+ * 登录(四选一):
11
+ * await client.login() // 小程序:自动 wx.login 换 token
12
+ * await client.login({ apiKey }) // Node / 脚本 / Web:appid 级密钥
13
+ * await client.pollScanLogin(sessionId) // Web:扫码登录(配合 createScanSession)
14
+ * udg.init({ ..., token }) // 外部体系已有 JWT 直入
15
+ *
16
+ * 之后:client.database().collection('users').where({...}).get() // → defaultDb
17
+ * client.database('maps').collection('layers').get() // → 显式 dbKey,同一份 token
18
+ * token 缓存 / 自动续期 / 自动重登由 SDK 内部处理,业务无感。
19
+ */
20
+ const { Database } = require('./database')
21
+ const { command, UdgRegExp } = require('./command')
22
+ const { rawPost, postAuthed, UdgRequestError } = require('./request')
23
+ const { AuthManager } = require('./auth')
24
+ const storage = require('./storage')
25
+
26
+ function genSessionId() {
27
+ try {
28
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
29
+ return crypto.randomUUID().replace(/-/g, '')
30
+ }
31
+ } catch (e) { /* fallthrough */ }
32
+ let s = ''
33
+ for (let i = 0; i < 32; i++) s += Math.floor(Math.random() * 16).toString(16)
34
+ return s
35
+ }
36
+
37
+ function sleep(ms) {
38
+ return new Promise((resolve) => setTimeout(resolve, ms))
39
+ }
40
+
41
+ /**
42
+ * appid / streetKey 二选一场景下,懒解析出 appid(仅 streetKey 时调用 /tenant/resolve)。
43
+ * 解析结果按 endpoint+streetKey 缓存(跨端持久化,见 storage.js),同一浏览器 tab/进程内不重复请求。
44
+ */
45
+ function ensureAppid(ctx) {
46
+ if (ctx.appid) return Promise.resolve(ctx.appid)
47
+ if (!ctx.streetKey) {
48
+ return Promise.reject(new Error('init 缺少必填参数 appid 或 streetKey'))
49
+ }
50
+ if (ctx._resolvingAppid) return ctx._resolvingAppid
51
+ const cacheKey = 'udg_resolve_' + ctx.streetKey + '@' + ctx.endpoint
52
+ ctx._resolvingAppid = (async () => {
53
+ let appid = storage.get(cacheKey)
54
+ if (!appid) {
55
+ const data = await rawPost(ctx)('/tenant/resolve', { streetKey: ctx.streetKey })
56
+ appid = data.appid
57
+ storage.set(cacheKey, appid)
58
+ }
59
+ ctx.appid = appid
60
+ if (ctx.auth) ctx.auth.rebindAppid()
61
+ return appid
62
+ })()
63
+ return ctx._resolvingAppid
64
+ }
65
+
66
+ class UdgClient {
67
+ constructor(options) {
68
+ const o = options || {}
69
+ if (!o.endpoint || typeof o.endpoint !== 'string') {
70
+ throw new Error('init 缺少必填参数 endpoint(UDG Gateway 地址)')
71
+ }
72
+ if (!o.appid && !o.streetKey) {
73
+ throw new Error('init 缺少必填参数 appid 或 streetKey(二选一;Web 多租户场景可只传 streetKey)')
74
+ }
75
+ this._ctx = {
76
+ endpoint: o.endpoint,
77
+ // 同时传 appid 与 streetKey 时以 appid 为准,忽略 streetKey(不调用 /tenant/resolve)
78
+ appid: o.appid || '',
79
+ streetKey: o.appid ? '' : (o.streetKey || ''),
80
+ defaultDb: o.defaultDb || '',
81
+ timeout: o.timeout || 15000
82
+ }
83
+ this._ctx.auth = new AuthManager(this._ctx, rawPost(this._ctx))
84
+ if (o.token) {
85
+ // 外部 token 直入(与现有 JWT 体系互通)
86
+ this._ctx.auth.setExternalToken(o.token)
87
+ }
88
+ }
89
+
90
+ /**
91
+ * @param {string} [dbKey] 目标数据源别名(租户 databases[] 中登记的 dbKey);
92
+ * 不传时用 init 传入的 defaultDb,两者都空则由 Gateway 用租户配置的 defaultDb
93
+ */
94
+ database(dbKey) {
95
+ return new Database(this._ctx, dbKey || this._ctx.defaultDb)
96
+ }
97
+
98
+ /* ===================== 认证 ===================== */
99
+
100
+ /**
101
+ * 登录。小程序环境无参调用(自动 wx.login);其他环境传 { apiKey }。
102
+ * 幂等:本地缓存 token 未过期时直接复用;{ force: true } 强制重登。
103
+ */
104
+ async login(opts) {
105
+ await ensureAppid(this._ctx)
106
+ return this._ctx.auth.login(opts)
107
+ }
108
+
109
+ /** 当前是否已持有有效 token */
110
+ isLoggedIn() {
111
+ return this._ctx.auth.isTokenValid()
112
+ }
113
+
114
+ /** 获取当前 token(如需传给其他系统) */
115
+ getToken() {
116
+ return this._ctx.auth.token
117
+ }
118
+
119
+ /** 外部体系刷新 token 后手动更新 */
120
+ setToken(token) {
121
+ this._ctx.auth.setExternalToken(token)
122
+ }
123
+
124
+ /** 退出登录(清除本地缓存的 token) */
125
+ logout() {
126
+ this._ctx.auth.logout()
127
+ }
128
+
129
+ /* ===================== 扫码登录(Web 端) ===================== */
130
+
131
+ /**
132
+ * 创建扫码会话:返回 sessionId,二维码内容由业务自行拼接渲染
133
+ * (各小程序扫码路由不同,如 `t=scanwebcode&id=${sessionId}&p=login`)。
134
+ */
135
+ createScanSession() {
136
+ return { sessionId: genSessionId() }
137
+ }
138
+
139
+ /** 返回 init 时的 streetKey(appid 直传场景为空字符串) */
140
+ getStreetKey() {
141
+ return this._ctx.streetKey || ''
142
+ }
143
+
144
+ /**
145
+ * 可选辅助:拼接与 MGAPIV3 兼容的二维码 query 内容(业务仍负责渲染为图片)。
146
+ * 默认格式:/publicfiles/webcode/{streetKey}/t=scanwebcode&id={sessionId}&p=login
147
+ * @param {object} opts { streetKey?(默认取 init 时的值), prefix?, action?, p?, base? }
148
+ */
149
+ buildScanQrContent(sessionId, opts) {
150
+ const o = opts || {}
151
+ const streetKey = o.streetKey || this._ctx.streetKey || ''
152
+ const prefix = (o.prefix || '/publicfiles/webcode').replace(/\/+$/, '')
153
+ const query = `t=${o.action || 'scanwebcode'}&id=${sessionId}&p=${o.p || 'login'}`
154
+ const path = streetKey ? `${prefix}/${streetKey}/${query}` : `${prefix}/${query}`
155
+ return o.base ? o.base.replace(/\/+$/, '') + path : path
156
+ }
157
+
158
+ /**
159
+ * 轮询扫码登录结果;确认后自动保存 token 并返回 { token, refreshToken, userInfo }。
160
+ * @param {string} sessionId createScanSession 返回的 id(即二维码中的 id)
161
+ * @param {object} opts { interval=2000, timeout=300000, onStatus(status) }
162
+ */
163
+ async pollScanLogin(sessionId, opts) {
164
+ await ensureAppid(this._ctx)
165
+ const o = opts || {}
166
+ const interval = o.interval || 2000
167
+ const timeout = o.timeout || 5 * 60 * 1000
168
+ const post = rawPost(this._ctx)
169
+ const start = Date.now()
170
+ for (;;) {
171
+ const data = await post('/auth/scan/statuscheck', {
172
+ appid: this._ctx.appid,
173
+ id: sessionId
174
+ })
175
+ if (typeof o.onStatus === 'function') o.onStatus(data.status)
176
+ if (data.status === 'confirmed') {
177
+ this._ctx.auth.setTokens(data.token, data.refreshToken, 'scan')
178
+ return { token: data.token, refreshToken: data.refreshToken, userInfo: data.userInfo }
179
+ }
180
+ if (data.status === 'expired') {
181
+ throw new UdgRequestError({ errorCode: 'SCAN_EXPIRED', errorMessage: '扫码会话已过期,请重新生成二维码' })
182
+ }
183
+ if (Date.now() - start > timeout) {
184
+ throw new UdgRequestError({ errorCode: 'SCAN_TIMEOUT', errorMessage: '扫码登录等待超时' })
185
+ }
186
+ await sleep(interval)
187
+ }
188
+ }
189
+
190
+ /* ===================== 扫码确认(小程序端) ===================== */
191
+
192
+ /**
193
+ * 一键确认 Web 扫码登录(需先 client.login()):
194
+ * 服务端代写 log 记录并为 Web 端签发 token,替代「wadd log + 请求 login 接口」两步。
195
+ * @param {object} params { id: 二维码中的 sessionId, admininfo: 管理员信息对象, extra? }
196
+ */
197
+ async approveScanLogin(params) {
198
+ const p = params || {}
199
+ if (!p.id || !p.admininfo) {
200
+ throw new UdgRequestError({ errorCode: 'INVALID_PARAM', errorMessage: 'approveScanLogin 需要 id 与 admininfo' })
201
+ }
202
+ await ensureAppid(this._ctx)
203
+ return postAuthed(this._ctx, '/auth/scan/approve', {
204
+ appid: this._ctx.appid,
205
+ id: p.id,
206
+ admininfo: p.admininfo,
207
+ extra: p.extra,
208
+ streetKey: p.streetKey
209
+ })
210
+ }
211
+ }
212
+
213
+ function init(options) {
214
+ return new UdgClient(options)
215
+ }
216
+
217
+ module.exports = { init, UdgClient, command, RegExp: UdgRegExp, UdgRequestError }
package/src/request.js ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * 跨端 HTTP 请求适配(外部 API 不变):
3
+ * - 微信小程序 → wx.request
4
+ * - Web / Node(>=18) → fetch
5
+ *
6
+ * 数据请求自动携带 token;遇 401/403 时自动 refresh → 重试 → 必要时自动重登(业务无感)。
7
+ */
8
+ const { encode, decode } = require('./serialize')
9
+
10
+ class UdgRequestError extends Error {
11
+ constructor(payload, httpStatus) {
12
+ super((payload && payload.errorMessage) || '请求失败')
13
+ this.name = 'UdgRequestError'
14
+ this.errorCode = (payload && payload.errorCode) || 'NETWORK_ERROR'
15
+ this.errorMessage = this.message
16
+ this.requestId = (payload && payload.requestId) || ''
17
+ this.timestamp = (payload && payload.timestamp) || new Date().toISOString()
18
+ this.httpStatus = httpStatus || 0
19
+ }
20
+ }
21
+
22
+ function isMiniProgram() {
23
+ // eslint-disable-next-line no-undef
24
+ return typeof wx !== 'undefined' && wx !== null && typeof wx.request === 'function'
25
+ }
26
+
27
+ function requestViaWx(url, body, headers, timeout) {
28
+ return new Promise((resolve, reject) => {
29
+ // eslint-disable-next-line no-undef
30
+ wx.request({
31
+ url,
32
+ method: 'POST',
33
+ data: body,
34
+ header: headers,
35
+ timeout,
36
+ success: (res) => resolve({ status: res.statusCode, json: res.data }),
37
+ fail: (err) =>
38
+ reject(new UdgRequestError({ errorCode: 'NETWORK_ERROR', errorMessage: err.errMsg || '网络请求失败' }))
39
+ })
40
+ })
41
+ }
42
+
43
+ async function requestViaFetch(url, body, headers, timeout) {
44
+ if (typeof fetch !== 'function') {
45
+ throw new UdgRequestError({
46
+ errorCode: 'ENV_NOT_SUPPORTED',
47
+ errorMessage: '当前环境不支持 fetch(Node 需 >= 18,或在微信小程序中使用)'
48
+ })
49
+ }
50
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null
51
+ const timer = controller ? setTimeout(() => controller.abort(), timeout) : null
52
+ try {
53
+ const res = await fetch(url, {
54
+ method: 'POST',
55
+ headers,
56
+ body: JSON.stringify(body),
57
+ signal: controller ? controller.signal : undefined
58
+ })
59
+ let json = null
60
+ try {
61
+ json = await res.json()
62
+ } catch (e) {
63
+ json = null
64
+ }
65
+ return { status: res.status, json }
66
+ } catch (err) {
67
+ if (err.name === 'AbortError') {
68
+ throw new UdgRequestError({ errorCode: 'TIMEOUT', errorMessage: `请求超时(${timeout}ms)` })
69
+ }
70
+ throw new UdgRequestError({ errorCode: 'NETWORK_ERROR', errorMessage: err.message || '网络请求失败' })
71
+ } finally {
72
+ if (timer) clearTimeout(timer)
73
+ }
74
+ }
75
+
76
+ /** 单次原始请求(不含自动续期逻辑) */
77
+ async function rawRequest(ctx, path, body, token) {
78
+ const url = ctx.endpoint.replace(/\/+$/, '') + path
79
+ const headers = { 'Content-Type': 'application/json' }
80
+ if (token) headers.Authorization = 'Bearer ' + token
81
+ const timeout = ctx.timeout || 15000
82
+ const { status, json } = isMiniProgram()
83
+ ? await requestViaWx(url, encode(body), headers, timeout)
84
+ : await requestViaFetch(url, encode(body), headers, timeout)
85
+ if (!json || json.success !== true) {
86
+ throw new UdgRequestError(
87
+ json || { errorCode: 'HTTP_' + status, errorMessage: 'Gateway 返回异常(HTTP ' + status + ')' },
88
+ status
89
+ )
90
+ }
91
+ return decode(json.data)
92
+ }
93
+
94
+ /** 无鉴权请求(登录 / 续期 / 扫码轮询等 auth 接口使用) */
95
+ function rawPost(ctx) {
96
+ return (path, body) => rawRequest(ctx, path, body, '')
97
+ }
98
+
99
+ /** 令牌确实失效(而非权限/策略类拒绝,如只读库写操作、黑名单库)才值得自动续期 */
100
+ function isAuthFailure(err) {
101
+ return err instanceof UdgRequestError && (err.errorCode === 'UNAUTHORIZED' || err.errorCode === 'FORBIDDEN')
102
+ }
103
+
104
+ /**
105
+ * 数据请求:自动注入 appid + token(db 由调用方 payload 携带,缺省时 Gateway 用租户 defaultDb);
106
+ * 令牌失效(errorCode 为 UNAUTHORIZED/FORBIDDEN)时自动 refresh 重试一次,refresh 失败再尝试自动重登。
107
+ */
108
+ async function post(ctx, path, payload) {
109
+ const body = Object.assign({ appid: ctx.appid }, payload)
110
+ const auth = ctx.auth
111
+ const token = auth ? auth.token : ''
112
+ if (!token) {
113
+ throw new UdgRequestError({
114
+ errorCode: 'NEED_LOGIN',
115
+ errorMessage: '尚未登录:请先调用 client.login()(或在 init 中传入 token)'
116
+ })
117
+ }
118
+ try {
119
+ return await rawRequest(ctx, path, body, token)
120
+ } catch (err) {
121
+ const authFailed = isAuthFailure(err)
122
+ if (!authFailed || !auth || auth.mode === 'external' || auth.mode === '') throw err
123
+
124
+ // ① 尝试续期
125
+ if (await auth.refresh()) {
126
+ return rawRequest(ctx, path, body, auth.token)
127
+ }
128
+ // ② 续期失败 → 自动重登(wechat / apikey 模式)
129
+ let reloggedIn = false
130
+ try {
131
+ reloggedIn = await auth.relogin()
132
+ } catch (e) {
133
+ reloggedIn = false
134
+ }
135
+ if (reloggedIn) {
136
+ return rawRequest(ctx, path, body, auth.token)
137
+ }
138
+ throw err
139
+ }
140
+ }
141
+
142
+ /** 带鉴权的 auth 类请求(如 scan/approve,需要已登录),不注入 dataSource */
143
+ async function postAuthed(ctx, path, payload) {
144
+ const auth = ctx.auth
145
+ if (!auth || !auth.token) {
146
+ throw new UdgRequestError({ errorCode: 'NEED_LOGIN', errorMessage: '尚未登录:请先调用 client.login()' })
147
+ }
148
+ try {
149
+ return await rawRequest(ctx, path, payload, auth.token)
150
+ } catch (err) {
151
+ const authFailed = isAuthFailure(err)
152
+ if (authFailed && auth.mode !== 'external' && (await auth.refresh())) {
153
+ return rawRequest(ctx, path, payload, auth.token)
154
+ }
155
+ throw err
156
+ }
157
+ }
158
+
159
+ module.exports = { post, postAuthed, rawPost, rawRequest, UdgRequestError }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * 传输序列化:Date ↔ { $date: 毫秒时间戳 }(与 Gateway 约定一致)。
3
+ */
4
+
5
+ function isPlainObject(v) {
6
+ return v !== null && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date)
7
+ }
8
+
9
+ /** 出站:Date → { $date: ms } */
10
+ function encode(value) {
11
+ if (value instanceof Date) return { $date: value.getTime() }
12
+ if (Array.isArray(value)) return value.map(encode)
13
+ if (value !== null && typeof value === 'object') {
14
+ const out = {}
15
+ for (const k of Object.keys(value)) out[k] = encode(value[k])
16
+ return out
17
+ }
18
+ return value
19
+ }
20
+
21
+ /** 入站:{ $date: ms } → Date */
22
+ function decode(value) {
23
+ if (Array.isArray(value)) return value.map(decode)
24
+ if (value !== null && typeof value === 'object') {
25
+ const keys = Object.keys(value)
26
+ if (keys.length === 1 && keys[0] === '$date' && typeof value.$date === 'number') {
27
+ return new Date(value.$date)
28
+ }
29
+ const out = {}
30
+ for (const k of keys) out[k] = decode(value[k])
31
+ return out
32
+ }
33
+ return value
34
+ }
35
+
36
+ module.exports = { encode, decode, isPlainObject }
package/src/storage.js ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * 跨端持久化存储(token 缓存用):
3
+ * - 微信小程序 → wx.setStorageSync / wx.getStorageSync
4
+ * - Web → localStorage
5
+ * - Node → 进程内存
6
+ */
7
+
8
+ const memoryStore = new Map()
9
+
10
+ function isMiniProgram() {
11
+ // eslint-disable-next-line no-undef
12
+ return typeof wx !== 'undefined' && wx !== null && typeof wx.setStorageSync === 'function'
13
+ }
14
+
15
+ function hasLocalStorage() {
16
+ try {
17
+ return typeof localStorage !== 'undefined' && localStorage !== null
18
+ } catch (e) {
19
+ return false
20
+ }
21
+ }
22
+
23
+ function get(key) {
24
+ try {
25
+ if (isMiniProgram()) {
26
+ // eslint-disable-next-line no-undef
27
+ const v = wx.getStorageSync(key)
28
+ return v ? JSON.parse(v) : null
29
+ }
30
+ if (hasLocalStorage()) {
31
+ const v = localStorage.getItem(key)
32
+ return v ? JSON.parse(v) : null
33
+ }
34
+ return memoryStore.get(key) || null
35
+ } catch (e) {
36
+ return null
37
+ }
38
+ }
39
+
40
+ function set(key, value) {
41
+ try {
42
+ if (isMiniProgram()) {
43
+ // eslint-disable-next-line no-undef
44
+ wx.setStorageSync(key, JSON.stringify(value))
45
+ } else if (hasLocalStorage()) {
46
+ localStorage.setItem(key, JSON.stringify(value))
47
+ } else {
48
+ memoryStore.set(key, value)
49
+ }
50
+ } catch (e) {
51
+ /* 存储失败不影响主流程 */
52
+ }
53
+ }
54
+
55
+ function remove(key) {
56
+ try {
57
+ if (isMiniProgram()) {
58
+ // eslint-disable-next-line no-undef
59
+ wx.removeStorageSync(key)
60
+ } else if (hasLocalStorage()) {
61
+ localStorage.removeItem(key)
62
+ } else {
63
+ memoryStore.delete(key)
64
+ }
65
+ } catch (e) {
66
+ /* ignore */
67
+ }
68
+ }
69
+
70
+ module.exports = { get, set, remove }