/** * 首页商品列表「当次登录」会话 —— 切 tab 不重复拉商品; * 城市 / 登录态变化或下拉刷新时再请求。logout 时 clear。 */ import Taro from '@tarojs/taro'; export type HomeCatalogCache = { cityCode: string; authKey: string; products: unknown[]; }; type HomeSession = { bootstrapped: boolean; cache: HomeCatalogCache | null; }; const STORAGE_KEY = 'dukang_home_catalog_session_v1'; let memory: HomeSession | null = null; function emptySession(): HomeSession { return { bootstrapped: false, cache: null }; } function readSession(): HomeSession { if (memory) return memory; try { const raw = Taro.getStorageSync(STORAGE_KEY); if (!raw) { memory = emptySession(); return memory; } const parsed = (typeof raw === 'string' ? JSON.parse(raw) : raw) as Partial; memory = { bootstrapped: !!parsed.bootstrapped, cache: (parsed.cache as HomeCatalogCache | null) ?? null, }; return memory; } catch { memory = emptySession(); return memory; } } function writeSession(next: HomeSession) { memory = next; try { Taro.setStorageSync(STORAGE_KEY, JSON.stringify(next)); } catch { /* ignore quota */ } } export function isHomeCatalogBootstrapped(): boolean { return readSession().bootstrapped; } export function getHomeCatalogCache(): HomeCatalogCache | null { return readSession().cache; } export function setHomeCatalogCache(cache: HomeCatalogCache): void { writeSession({ bootstrapped: true, cache }); } export function resetHomeCatalogBootstrap(): void { memory = emptySession(); try { Taro.removeStorageSync(STORAGE_KEY); } catch { /* ignore */ } }