Files
doodle-mini/miniprogram/app.ts
T

145 lines
4.2 KiB
TypeScript

import { defaultPrintConfig } from './config/config';
import { getUser } from './utils/auth';
import { generateUUID, getAppUUID, setAppUUID } from './utils/uuid';
const STORAGE_KEY_PAGE_CONFIG = 'pageConfig';
// Pending resolvers for getPageConfig() callers waiting on config
let _configResolvers: Array<(config: PageConfigData | null) => void> = [];
// app.ts
App<IAppOption>({
globalData: {
env: 'release',
uuid: '',
user: null,
printConfig: defaultPrintConfig,
pageConfig: undefined,
pageConfigReady: false,
},
onLaunch() {
wx.cloud.init({
env: 'cloud1-9gifs7a2756e2c87',
traceUser: true,
});
const accountInfo = wx.getAccountInfoSync();
const env = accountInfo.miniProgram.envVersion || 'release';
this.globalData.env = env;
let uuid = getAppUUID();
if (!uuid) {
uuid = generateUUID();
setAppUUID(uuid);
console.log('生成并存储 UUID', uuid);
}
this.globalData.uuid = uuid;
if (env !== 'release') {
const printConfig =
wx.getStorageSync('printConfig') || defaultPrintConfig;
this.globalData.printConfig = printConfig;
}
// 静默登录(不阻塞页面渲染)
getUser()
.then((user) => {
this.globalData.user = user;
})
.catch((err) => {
console.error('静默登录失败', err);
});
void this.loadPageConfig();
},
onShow() {},
onHide() {},
getPrintConfig(): PrintConfig {
return this.globalData.printConfig || defaultPrintConfig;
},
setPrintConfig(config: PrintConfig) {
this.globalData.printConfig = config;
wx.setStorageSync('printConfig', config);
},
async loadPageConfig() {
let config: PageConfigData | null = null;
// L1: 数据预拉取
try {
const res = await new Promise<{ fetchedData: string }>(
(resolve, reject) => {
wx.getBackgroundFetchData({
fetchType: 'pre',
success: resolve as any,
fail: reject,
});
},
);
if (res.fetchedData) {
const parsed = JSON.parse(res.fetchedData);
config = parsed?.data || parsed;
}
} catch {
// 预拉取失败,继续降级
}
// L2: storage 缓存
if (!config) {
try {
const cached = wx.getStorageSync(STORAGE_KEY_PAGE_CONFIG);
if (cached && typeof cached === 'object') {
config = cached;
}
} catch {
// storage 读取失败,继续降级
}
}
// L3: 云函数兜底
if (!config) {
try {
const res = (await wx.cloud.callFunction({
name: 'pageConfigFetch',
})) as { result?: { success?: boolean; data?: any } };
if (res.result?.success && res.result.data) {
config = res.result.data;
}
} catch {
// 云函数也失败,config 保持 null
}
}
// 写入 globalData
if (config) {
this.globalData.pageConfig = config;
// 成功获取后写入 storage 缓存
try {
wx.setStorageSync(STORAGE_KEY_PAGE_CONFIG, config);
} catch {
// storage 写入失败不影响主流程
}
}
// 标记就绪,通知等待中的页面
this.globalData.pageConfigReady = true;
for (const resolve of _configResolvers) {
resolve(config);
}
_configResolvers = [];
},
getPageConfig(): Promise<PageConfigData | null> {
if (this.globalData.pageConfigReady) {
return Promise.resolve(this.globalData.pageConfig || null);
}
return new Promise((resolve) => {
_configResolvers.push(resolve);
});
},
});