@chenminai/cloud-shared 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.
Files changed (3) hide show
  1. package/auth.js +34 -0
  2. package/index.js +1 -0
  3. package/package.json +12 -0
package/auth.js ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * 云函数用户身份解析工具
3
+ *
4
+ * 统一处理小程序(openid → cbAuthUid)和 Web 端(_webUserId / _cbAuthUid)两种调用方式。
5
+ * 在每个需要用户身份的云函数中 require 此模块,避免重复代码。
6
+ */
7
+
8
+ const cloud = require('wx-server-sdk')
9
+ const db = cloud.database()
10
+
11
+ /**
12
+ * 解析调用方的 cbAuthUid:
13
+ * - 小程序调用:通过 wxContext.OPENID 查 users 表取 cbAuthUid
14
+ * - Web 端调用:直接使用 params._cbAuthUid(或兼容旧字段 _webUserId)
15
+ *
16
+ * @param {object} wxContext cloud.getWXContext() 的返回值
17
+ * @param {object} params event 解析后的参数对象
18
+ * @returns {Promise<string|null>} cbAuthUid,或 null(无法识别身份)
19
+ */
20
+ async function resolveUserId(wxContext, params) {
21
+ if (wxContext.OPENID) {
22
+ const result = await db.collection('users')
23
+ .where({ openid: wxContext.OPENID })
24
+ .field({ cbAuthUid: true })
25
+ .limit(1)
26
+ .get()
27
+ const cbAuthUid = result.data[0]?.cbAuthUid
28
+ return cbAuthUid ?? null
29
+ }
30
+ // Web 端:优先 _cbAuthUid,兼容旧字段 _webUserId
31
+ return params._cbAuthUid || params._webUserId || null
32
+ }
33
+
34
+ module.exports = { resolveUserId }
package/index.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./auth')
package/package.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@chenminai/cloud-shared",
3
+ "version": "1.0.0",
4
+ "description": "云函数共享工具:用户身份解析等",
5
+ "main": "index.js",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "dependencies": {
10
+ "wx-server-sdk": "~2.6.3"
11
+ }
12
+ }