Files
YelayMaths/yelaymaths/app.js
T
2026-10-01 11:33:12 +08:00

86 lines
2.6 KiB
JavaScript

// app.js
const api = require('./utils/api');
const store = require('./utils/store');
App({
globalData: {
/** 初始化完成的 Promise,页面 onLoad 里等它即可,避免首屏读不到数据 */
ready: null,
},
onLaunch() {
this.globalData.ready = this.bootstrap();
this.watchUpdates();
},
/**
* 版本更新监听。**只在这里注册一次**。
*
* 以前写在首页的 onShow 里,每切回首页就注册一遍;微信这个接口不去重,
* 回调会一层层叠加,同一次更新会连着弹好几个弹窗。放在 App 里天然只执行一次。
*
* 提示文案来自后台配置,所以要等启动流程把配置读回来再弹,避免弹出空白内容。
*/
watchUpdates() {
const updateManager = wx.getUpdateManager();
updateManager.onUpdateReady(() => {
void this.ready().then(() => {
wx.showModal({
title: store.cfg('app.update.title'),
showCancel: false,
content: store.cfg('app.update.content'),
success: (res) => {
if (res.confirm) updateManager.applyUpdate();
},
});
});
});
updateManager.onUpdateFailed(() => {
void this.ready().then(() => {
wx.showModal({
title: store.cfg('app.update.title'),
showCancel: false,
content: store.cfg('app.update.failed'),
});
});
});
},
/**
* 启动流程:配置再静默登录,最后拉已购课程。
*
* 每一步失败都不阻断启动:配置缺失时页面按空值渲染,登录失败时按未登录渲染。
* 旧版本在页面 data 里同步读缓存、而缓存由异步写入,首次安装必然报错,这里不再重蹈。
*/
bootstrap() {
const tasks = [
api
.getConfig()
.then((cfg) => store.setSiteConfig(cfg))
.catch((err) => console.warn('[app] 配置加载失败', err)),
api
.login()
.then((res) => {
// 静默登录只建立身份。用户从没主动登录过、或者已经退出,就不去拉已购课程,
// 否则知识页会在「未登录」状态下又冒出课程列表。
if (!res || !res.user || res.user.isLogin !== 1) {
store.setEntitlements([]);
return null;
}
return api.getEntitlements().then((list) => store.setEntitlements(list));
})
.catch((err) => console.warn('[app] 登录或权益加载失败', err)),
];
return Promise.all(tasks);
},
/** 页面调用它确保初始化完成。 */
ready() {
return this.globalData.ready || Promise.resolve();
},
});