修复云端数据一致性问题

This commit is contained in:
2026-07-29 11:03:44 +08:00
parent a3dd080b6f
commit 17727ab1dd
12 changed files with 389 additions and 41 deletions
+19
View File
@@ -0,0 +1,19 @@
const crypto = require('crypto')
const memberKey = (openid) =>
crypto.createHash('sha256').update(String(openid || '')).digest('hex')
const publicEntry = (entry) => {
if (!entry) return null
const { memberKey: _memberKey, openid: _openid, ...publicData } = entry
return publicData
}
const publicRanked = (ranked) => (ranked || []).map(publicEntry)
const findMyEntry = (ranked, key) => {
const item = (ranked || []).find(entry => entry.memberKey === key)
return item ? { ...publicEntry(item), isMe: true } : null
}
module.exports = { memberKey, publicEntry, publicRanked, findMyEntry }
+13 -14
View File
@@ -1,4 +1,5 @@
const cloud = require('wx-server-sdk')
const { memberKey, publicEntry, publicRanked, findMyEntry } = require('./data')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command
@@ -201,6 +202,7 @@ const _buildFromScan = async (latestByOpenid, period, limit, myOpenid) => {
// Top N for the board
const ranked = allSorted.slice(0, limit).map((item, i) => ({
rank: i + 1,
memberKey: memberKey(item.openid),
isMe: item.openid === myOpenid,
nickname: item.nickname || '',
name: _displayName(item),
@@ -273,21 +275,13 @@ const _serveFromSnapshot = async (period, limit, myOpenid) => {
if (!data || !Array.isArray(data.ranked)) return null
const age = data.updatedAt ? Date.now() - new Date(data.updatedAt).getTime() : Infinity
if (Number.isFinite(age) && age > SNAPSHOT_TTL_MS) return null // 过期 → 实时
const ranked = data.ranked.slice(0, limit).map(item => ({
const key = memberKey(myOpenid)
const snapshotRanked = data.ranked.slice(0, limit)
const ranked = publicRanked(snapshotRanked).map((item, i) => ({
...item,
isMe: item.openid === myOpenid
isMe: snapshotRanked[i].memberKey === key
}))
const me = ranked.find(r => r.openid === myOpenid)
const myEntry = me ? {
rank: me.rank,
openid: me.openid,
nickname: me.nickname || '',
name: me.name,
duration: me.duration,
sessions: me.sessions,
avatarUrl: me.avatarUrl || '',
isMe: true
} : null
const myEntry = findMyEntry(data.ranked, key)
return { period, ranked, myOpenid, myEntry, updatedAt: data.updatedAt }
} catch (e) {
return null
@@ -318,7 +312,12 @@ const _computeBoard = async (period, limit, myOpenid, opts) => {
const result = await _buildFromScan(latestByOpenid, period, limit, myOpenid)
const nowIso = new Date().toISOString()
if (opts.persist) await _persistSnapshot(period, result)
return { period, ranked: result.ranked, myOpenid, myEntry: result.myEntry, updatedAt: nowIso }
return {
period,
ranked: publicRanked(result.ranked),
myEntry: publicEntry(result.myEntry),
updatedAt: nowIso
}
}
exports.main = async (event) => {