/** * 极简全局状态。 * * 替代旧版本在各页面直接读写 wx.getStorageSync 的做法: * 统一从内存读、同步落盘,页面只与这里交互。 */ const config = require('../config/index'); const memory = { user: null, siteConfig: null, entitlements: [], }; const listeners = new Set(); function notify() { listeners.forEach((fn) => { try { fn(); } catch (e) { console.error('[store] 监听器执行失败', e); } }); } function read(key, fallback) { try { const v = wx.getStorageSync(key); return v === '' || v === undefined || v === null ? fallback : v; } catch (e) { return fallback; } } const store = { // ── token ──────────────────────────────────────────────────────────── getToken: () => read(config.STORAGE.TOKEN, ''), getRefreshToken: () => read(config.STORAGE.REFRESH_TOKEN, ''), setTokens(accessToken, refreshToken) { wx.setStorageSync(config.STORAGE.TOKEN, accessToken); if (refreshToken) wx.setStorageSync(config.STORAGE.REFRESH_TOKEN, refreshToken); }, clearTokens() { wx.removeStorageSync(config.STORAGE.TOKEN); wx.removeStorageSync(config.STORAGE.REFRESH_TOKEN); }, isLoggedIn: () => !!read(config.STORAGE.TOKEN, ''), // ── 用户 ───────────────────────────────────────────────────────────── getUser() { if (memory.user) return memory.user; memory.user = read(config.STORAGE.USER, null); return memory.user; }, setUser(user) { memory.user = user; wx.setStorageSync(config.STORAGE.USER, user); notify(); }, // ── 站点配置 ───────────────────────────────────────────────────────── getSiteConfig() { if (memory.siteConfig) return memory.siteConfig; memory.siteConfig = read(config.STORAGE.CONFIG, {}); return memory.siteConfig; }, setSiteConfig(cfg) { memory.siteConfig = cfg || {}; wx.setStorageSync(config.STORAGE.CONFIG, memory.siteConfig); notify(); }, /** 取配置项,带兜底值,避免配置缺失时页面直接崩掉。 */ cfg(key, fallback) { const value = store.getSiteConfig()[key]; return value === undefined || value === '' ? (fallback === undefined ? '' : fallback) : value; }, // ── 已购课程 ───────────────────────────────────────────────────────── getEntitlements() { if (memory.entitlements && memory.entitlements.length) return memory.entitlements; memory.entitlements = read(config.STORAGE.ENTITLEMENTS, []) || []; return memory.entitlements; }, setEntitlements(list) { memory.entitlements = list || []; wx.setStorageSync(config.STORAGE.ENTITLEMENTS, memory.entitlements); notify(); }, hasCourse(code) { return store.getEntitlements().some((item) => item.code === code); }, // ── 订阅与清理 ─────────────────────────────────────────────────────── subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); }, reset() { memory.user = null; memory.siteConfig = null; memory.entitlements = []; store.clearTokens(); wx.removeStorageSync(config.STORAGE.USER); wx.removeStorageSync(config.STORAGE.ENTITLEMENTS); notify(); }, }; module.exports = store;