Files
wx_pbzc/utils/cloud.js
T

105 lines
2.8 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
console.log('[cloud] init ok')
} catch (e) {
console.error('[cloud] init failed:', e)
_enabled = false
}
}
const pullAll = async () => {
const db = getDb()
if (!db) return null
try {
console.log('[cloud] pulling data...')
const res = await db.collection(DB_COLLECTION)
.where({ _openid: '{openid}' })
.get()
console.log('[cloud] pull result:', res.data.length, 'docs')
return res.data.length > 0 ? res.data[0] : null
} catch (e) {
console.warn('[cloud] pull skipped (collection may not exist yet):', e.errMsg || e.message)
return null
}
}
const pushAll = () => {
if (!_enabled) return
if (_pushTimer) clearTimeout(_pushTimer)
_pushTimer = setTimeout(() => _doPush(), 2000)
}
const _doPush = async () => {
const db = getDb()
if (!db) return
console.log('[cloud] pushing data...')
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()
}
try {
const addRes = await db.collection(DB_COLLECTION).add({ data })
console.log('[cloud] push ok (new doc):', addRes._id)
} catch (addErr) {
console.log('[cloud] add returned error, trying update...')
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 })
console.log('[cloud] push ok (updated doc):', existing.data[0]._id)
} else {
console.error('[cloud] push failed: no doc found to update')
}
}
} catch (e) {
console.error('[cloud] push error:', e.errMsg || e.message)
}
}
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()
console.log('[cloud] cleared')
}
} catch (e) {
console.warn('[cloud] clear skipped:', e.errMsg || e.message)
}
}
module.exports = { init, pullAll, pushAll, clearAll, get enabled() { return _enabled } }