UNPKG

@cloudcome/utils-browser

Version:
88 lines (87 loc) 2.42 kB
"use strict"; Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); const cache = require("@cloudcome/utils-core/cache"); class StorageCache extends cache.AbstractCache { /** * 创建一个新的 StorageCache 实例 * @param storage - 使用的存储实现(localStorage 或 sessionStorage) * @param namespace - 可选,用于为缓存键添加前缀的命名空间 */ constructor(storage, namespace = "") { super(); this.storage = storage; this.namespace = namespace; } /** * 通过ID获取缓存数据 * @param id - 要获取的缓存键 * @returns 如果找到且未过期则返回缓存数据,否则返回null */ get(id) { const { storage, namespace } = this; const fullId = namespace ? `${namespace}:${id}` : id; try { const cachedString = storage.getItem(fullId); if (!cachedString) return null; const cached = JSON.parse(cachedString); if (cached.createdAt + cached.maxAge < Date.now()) { this.del(id); return null; } return cached; } catch (e) { return null; } } /** * 将数据存储到缓存中 * @param id - 存储数据使用的缓存键 * @param data - 要缓存的数据 * @param options - 可选的缓存配置 * @returns 成功返回true,存储失败返回false */ set(id, data, options) { const { storage, namespace } = this; const fullId = namespace ? `${namespace}:${id}` : id; try { storage.setItem( fullId, JSON.stringify({ id, data, createdAt: Date.now(), maxAge: options?.maxAge || 0 }) ); } catch (cause) { } } /** * 通过ID删除缓存数据 * @param id - 要删除的缓存键 */ del(id) { const { storage, namespace } = this; const fullId = namespace ? `${namespace}:${id}` : id; try { storage.removeItem(fullId); } catch (cause) { } } clear() { try { this.storage.clear(); } catch (err) { } } } function createLocalCache(namespace) { return new StorageCache(localStorage, namespace); } function createSessionCache(namespace) { return new StorageCache(sessionStorage, namespace); } exports.StorageCache = StorageCache; exports.createLocalCache = createLocalCache; exports.createSessionCache = createSessionCache; //# sourceMappingURL=cache.cjs.map