UNPKG

@truenewx/tnxcore

Version:

互联网技术解决方案:JavaScript核心扩展支持

97 lines (88 loc) 2.61 kB
export const SessionStorage = { get(key: string): any | null { if (key) { const s = sessionStorage.getItem(key); if (s !== null) { try { return JSON.parse(s); } catch (e) { console.warn(e); } } } return null; }, set(key: string, value: any): void { if (key) { try { sessionStorage.setItem(key, JSON.stringify(value)); } catch (e) { console.warn(e); } } }, remove(key: string): void { if (key) { sessionStorage.removeItem(key); } }, clear(): void { sessionStorage.clear(); }, } export const LocalStorage = { get(key: string): any | null { if (key) { const s = localStorage.getItem(key); if (s !== null) { try { const v = JSON.parse(s); if (v && typeof v === 'object' && 'expiresAt' in v) { const expiresAt = v.expiresAt; const ts = Date.parse(expiresAt); if (!isNaN(ts) && Date.now() >= ts) { localStorage.removeItem(key); return null; } } if (v && typeof v === 'object' && 'value' in v) { return v.value; } return v; } catch (e) { console.warn(e); } } } return null; }, set(key: string, value: any, timeout?: number): void { if (key) { let payload: any = value; if (typeof timeout === 'number' && timeout > 0) { const expires = new Date(Date.now() + timeout); payload = { value, expiresAt: expires.toISOString(), } } try { localStorage.setItem(key, JSON.stringify(payload)); } catch (e) { console.warn(e); } } }, remove(key: string): void { if (key) { localStorage.removeItem(key); } }, clear(): void { localStorage.clear(); }, } export default { session: SessionStorage, local: LocalStorage, }