const DB_COLLECTION = 'plank_data' let _db = null let _pushTimer = null let _enabled = false let _openid = null const getDb = () => { if (!_enabled) return null if (!_db) { try { _db = wx.cloud.database() } catch (e) { _enabled = false } } return _db } /** * Call once from app.js onLaunch to initialize cloud. */ const init = () => { try { wx.cloud.init({ env: 'cloudbase-d1g56kl2q8f4f7d8a', traceUser: true }) _enabled = true } catch (e) { _enabled = false } } /** * Pull all user data from cloud. Returns null if no data or unavailable. * Collection is auto-created by first push, so .get() on empty collection * is safe — it just returns empty set. */ const pullAll = async () => { const db = getDb() if (!db) return null try { const res = await db.collection(DB_COLLECTION) .where({ _openid: '{openid}' }) .get() if (res && res.data && res.data.length > 0) { return res.data[0] } return null } catch (e) { // Collection may not exist yet — that's fine, first push will create it return null } } /** * Schedule a push (debounced 2s). */ 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() } // Strategy: try add() first. On first use, this auto-creates the // collection. If the user already has a doc, it returns // 'duplicate' error; we fall back to update via query. try { await db.collection(DB_COLLECTION).add({ data }) } catch (addErr) { // Likely already has a doc — find and update it 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 }) } } } catch (e) { // Silently ignore — data stays in local storage, will retry next write } } /** * Delete all cloud data for current user. */ 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) { // Collection or doc missing — nothing to clear } } module.exports = { init, pullAll, pushAll, clearAll, get enabled() { return _enabled } }