fix: 修复排行榜数据自增长(冷启动重复创建云端文档)

每次小程序冷启动都会为同一用户创建新的云端文档,
导致 leaderboard 把同一份数据累加 N 次。

改动:
- app.js: onLaunch 改为 async,每次启动先 pullAll 填充 _openid / _docId 缓存
- utils/cloud.js: 引入 _ensureOpenid() 单次解析;_doPush 总是先按 openid
  定位现有文档;update 失败不再回退到 add()(避免创建重复文档)
- utils/storage.js: getTodayRecord 按日期部分比较,修复一天第二次训练
This commit is contained in:
liucheng
2026-06-21 22:56:51 +08:00
parent 47f718a129
commit 6d1992869e
6 changed files with 259 additions and 57 deletions
+23 -8
View File
@@ -3,7 +3,7 @@ const cloud = require('./utils/cloud')
const storage = require('./utils/storage')
App({
onLaunch() {
async onLaunch() {
// Init cloud storage (no-op if not configured)
cloud.init()
@@ -28,14 +28,29 @@ App({
this.globalData.theme = themeMod.getCurrentTheme()
// Sync with cloud: pull on empty local, push on non-empty local
// Sync with cloud: always locate our doc first (pullAll caches
// _openid / _docId), then either restore or push. The previous flow
// only pulled when local was empty, so on a cold start with non-empty
// local it pushed without locating — and because the module-level
// _openid / _docId caches had been reset, pushAll fell through to
// add() and created a duplicate cloud doc every cold start. The
// leaderboard then summed duration across N docs for the same user.
const records = wx.getStorageSync('training_records')
if (!records || Object.keys(records).length === 0) {
// Case 1: Fresh install — restore from cloud
cloud.pullAll().then(cloudData => this._restoreFromCloud(cloudData))
} else {
// Case 2: Has local data — push to cloud (local is authoritative)
cloud.pushAll()
if (cloud.enabled) {
try {
const cloudData = await cloud.pullAll()
if (!records || Object.keys(records).length === 0) {
// Case 1: Fresh install (or user cleared local) — restore from cloud
this._restoreFromCloud(cloudData)
} else {
// Case 2: Has local data — push to cloud (local is authoritative)
// pullAll already populated _openid / _docId, so pushAll will
// update the existing doc instead of creating a duplicate.
cloud.pushAll()
}
} catch (e) {
console.error('Cloud sync on launch failed:', e)
}
}
},