103 lines
2.5 KiB
JavaScript
103 lines
2.5 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
|
|
}
|
|
|
|
/**
|
|
* Call once from app.js onLaunch to initialize cloud.
|
|
* Gracefully degrades if cloud environment isn't configured yet.
|
|
*/
|
|
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 cloud is unavailable or no data exists.
|
|
*/
|
|
const pullAll = async () => {
|
|
const db = getDb()
|
|
if (!db) return null
|
|
try {
|
|
const coll = db.collection(DB_COLLECTION)
|
|
const res = await coll.where({ _openid: '{openid}' }).get()
|
|
if (res && res.data && res.data.length > 0) {
|
|
return res.data[0]
|
|
}
|
|
return null
|
|
} catch (e) {
|
|
console.error('Cloud pull failed:', e)
|
|
return null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Schedule a cloud push (debounced at 2s).
|
|
* Call this after any local data mutation.
|
|
*/
|
|
const pushAll = () => {
|
|
if (!_enabled) return
|
|
if (_pushTimer) clearTimeout(_pushTimer)
|
|
_pushTimer = setTimeout(() => _doPush(), 2000)
|
|
}
|
|
|
|
const _doPush = async () => {
|
|
const db = getDb()
|
|
if (!db) return
|
|
try {
|
|
// Lazily require to avoid circular dependency at module-load time
|
|
const storage = require('./storage')
|
|
const themeMod = require('./theme')
|
|
|
|
const data = {
|
|
records: storage.getRecords(),
|
|
settings: storage.getSettings(),
|
|
streak: storage.getStreak(),
|
|
themeId: themeMod.getCurrentTheme().id,
|
|
updatedAt: new Date()
|
|
}
|
|
|
|
const coll = db.collection(DB_COLLECTION)
|
|
const existing = await coll.where({ _openid: '{openid}' }).get()
|
|
if (existing && existing.data && existing.data.length > 0) {
|
|
await coll.doc(existing.data[0]._id).update({ data })
|
|
} else {
|
|
await coll.add({ data })
|
|
}
|
|
} catch (e) {
|
|
console.error('Cloud push failed:', e)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Delete all cloud data for current user.
|
|
*/
|
|
const clearAll = async () => {
|
|
const db = getDb()
|
|
if (!db) return
|
|
try {
|
|
const coll = db.collection(DB_COLLECTION)
|
|
const existing = await coll.where({ _openid: '{openid}' }).get()
|
|
if (existing && existing.data && existing.data.length > 0) {
|
|
await coll.doc(existing.data[0]._id).remove()
|
|
}
|
|
} catch (e) {
|
|
console.error('Cloud clear failed:', e)
|
|
}
|
|
}
|
|
|
|
module.exports = { init, pullAll, pushAll, clearAll, get enabled() { return _enabled } }
|