Files
wx_pbzc/utils/cloud.js
T
lc 90e0e64156 fix: correct cloud upsert — query then update/add per user
Before: add-first-then-update caused duplicate docs on each push
because add() always succeeds once collection exists.

Now: query {_openid} first → update if found, add if not.
Each user always has exactly one document in plank_data.

Also removed debug console.log — only production-scale errors remain.
2026-06-04 17:41:29 +08:00

92 lines
2.1 KiB
JavaScript

const DB_COLLECTION = 'plank_data'
let _db = null
let _pushTimer = null
let _enabled = false
const getDb = () => {
if (!_enabled) return null
if (!_db) {
try { _db = wx.cloud.database() } catch (e) { _enabled = false }
}
return _db
}
const init = () => {
try {
wx.cloud.init({ env: 'cloudbase-d1g56kl2q8f4f7d8a', traceUser: true })
_enabled = true
} catch (e) {
_enabled = false
}
}
const pullAll = async () => {
const db = getDb()
if (!db) return null
try {
const res = await db.collection(DB_COLLECTION)
.where({ _openid: '{openid}' })
.get()
return (res && res.data && res.data.length > 0) ? res.data[0] : null
} catch (e) {
return null
}
}
const pushAll = () => {
if (!_enabled) return
if (_pushTimer) clearTimeout(_pushTimer)
_pushTimer = setTimeout(() => _doPush(), 2000)
}
const _doPush = async () => {
const db = getDb()
if (!db) return
try {
const storage = require('./storage')
const themeMod = require('./theme')
const data = {
records: storage.getRecords(),
settings: storage.getSettings(),
streak: storage.getStreak(),
themeId: themeMod.getCurrentTheme().id,
updatedAt: db.serverDate()
}
// Query then upsert: one doc per user
const existing = await db.collection(DB_COLLECTION)
.where({ _openid: '{openid}' })
.get()
if (existing && existing.data && existing.data.length > 0) {
await db.collection(DB_COLLECTION)
.doc(existing.data[0]._id)
.update({ data })
} else {
await db.collection(DB_COLLECTION).add({ data })
}
} catch (e) {
// Silently retry on next write
}
}
const clearAll = async () => {
const db = getDb()
if (!db) return
try {
const existing = await db.collection(DB_COLLECTION)
.where({ _openid: '{openid}' })
.get()
if (existing && existing.data && existing.data.length > 0) {
await db.collection(DB_COLLECTION)
.doc(existing.data[0]._id)
.remove()
}
} catch (e) {
// Nothing to clear
}
}
module.exports = { init, pullAll, pushAll, clearAll, get enabled() { return _enabled } }