feat: cloud sync with WeChat CloudBase — data survives app deletion
Problem: All data stored in wx.StorageSync is permanently lost when
user deletes the mini-program or clears cache.
Solution: Sync data to WeChat CloudBase (wx.cloud.database).
- Graceful degradation: if cloud env isn't configured, all local
storage works exactly as before.
- On app launch: if local records are empty, pull from cloud.
- On writes: push to cloud (debounced 2s) after saveRecord,
deleteRecord, saveSettings, updateStreak, setTheme.
- Clear data in settings also clears cloud.
Files:
- utils/cloud.js: cloud sync wrapper (init, pullAll, pushAll, clearAll)
- app.js: cloud.init() + restore on fresh install
- utils/storage.js: cloud.pushAll() after every mutation
- utils/theme.js: cloud.pushAll() after setTheme
- pages/settings/settings.js: cloud.clearAll() when clearing data
- project.config.json: cloudfunctionRoot added
Setup required (one-time in WeChat DevTools):
1. Open 'Cloud Development' panel → enable CloudBase
2. Create environment → copy env ID
3. In app.js, change wx.cloud.init() → wx.cloud.init({ env: 'YOUR-ENV-ID' })
4. Create 'plank_data' collection in cloud database
5. Set collection permission to 'Only creator can read/write'
This commit is contained in:
@@ -1,7 +1,11 @@
|
||||
const themeMod = require('./utils/theme')
|
||||
const cloud = require('./utils/cloud')
|
||||
|
||||
App({
|
||||
onLaunch() {
|
||||
// Init cloud storage (no-op if not configured)
|
||||
cloud.init()
|
||||
|
||||
const settings = wx.getStorageSync('user_settings')
|
||||
if (!settings) {
|
||||
wx.setStorageSync('user_settings', {
|
||||
@@ -12,11 +16,37 @@ App({
|
||||
vibrate: true
|
||||
})
|
||||
}
|
||||
|
||||
const streak = wx.getStorageSync('current_streak')
|
||||
if (!streak) {
|
||||
wx.setStorageSync('current_streak', { count: 0, lastDate: '' })
|
||||
}
|
||||
|
||||
this.globalData.theme = themeMod.getCurrentTheme()
|
||||
|
||||
// If local records are empty, try pulling from cloud
|
||||
const records = wx.getStorageSync('training_records')
|
||||
if (!records || Object.keys(records).length === 0) {
|
||||
cloud.pullAll().then((cloudData) => {
|
||||
if (!cloudData) return
|
||||
try {
|
||||
if (cloudData.records && Object.keys(cloudData.records).length > 0) {
|
||||
wx.setStorageSync('training_records', cloudData.records)
|
||||
}
|
||||
if (cloudData.settings) {
|
||||
wx.setStorageSync('user_settings', cloudData.settings)
|
||||
}
|
||||
if (cloudData.streak) {
|
||||
wx.setStorageSync('current_streak', cloudData.streak)
|
||||
}
|
||||
if (cloudData.themeId) {
|
||||
themeMod.setTheme(cloudData.themeId)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Cloud restore failed:', e)
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
globalData: {
|
||||
|
||||
Reference in New Issue
Block a user