UNPKG

@codelet/core

Version:
85 lines (84 loc) 2.09 kB
import { isArray, isObject } from '@daysnap/utils'; import { col } from '../codelet'; export class Storage { key; value = null; options = { debug: false, cached: false }; constructor(key, options) { const { initialValue, ...rest } = options || {}; this.key = key; if (options) { Object.assign(this.options, rest); } if (initialValue != undefined) { this.setItem(initialValue); } } _debug(...args) { if (this.options.debug) { console.log(`【Storage】=> `, ...args); } } /** * 设置值 */ setItem(val) { col.setStorageSync(this.key, val); if (this.options.cached) { this.value = this.getItem(); } return val; } getItem(defaultVal) { const val = col.getStorageSync(this.key) || null; if (val === null) { return defaultVal ?? null; } return val; } /** * 删除值 */ removeItem() { this.value = null; col.removeStorageSync(this.key); } /** * 更新值 */ updateItem(val) { this.value = null; const oldVal = this.getItem(); if (isArray(val) && isArray(oldVal)) { val = [...oldVal, ...val]; } else if (isObject(val) && isObject(oldVal)) { val = { ...oldVal, ...val }; } return this.setItem(val); } getItemOnce(defaultVal) { const val = this.getItem(defaultVal); this.removeItem(); return val; } getItemWithCache(defaultVal) { if (this.value !== null) { this._debug(`${this.key}: 命中缓存!`); return this.value; } this._debug(`${this.key}: 读取存储!`); const val = this.getItem(); if (val === null) { return defaultVal ?? null; } this.value = val; return this.value; } /** * 清除缓存 */ clearCache() { this.value = null; } }