@daysnap/utils
Version:
96 lines (86 loc) • 2.51 kB
JavaScript
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } var _class;
var _chunk5PB5B4HHcjs = require('./chunk-5PB5B4HH.cjs');
var _chunkOSEQ7XR6cjs = require('./chunk-OSEQ7XR6.cjs');
// src/storage/storage.ts
var Storage = (_class = class {
__init() {this.value = null}
__init2() {this.options = { debug: false, cached: false }}
constructor(key, storage, options) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);
const { initialValue, ...rest } = options || {};
this.key = key;
this.storage = storage;
if (options) {
Object.assign(this.options, rest);
}
if (initialValue != void 0) {
this.setItem(initialValue);
}
}
_debug(...args) {
if (this.options.debug) {
console.log(`\u3010Storage\u3011=> `, ...args);
}
}
/**
* 设置值
*/
setItem(val) {
this.storage.setItem(this.key, JSON.stringify(val));
if (this.options.cached) {
this.value = this.getItem();
}
return val;
}
getItem(defaultVal) {
const val = _nullishCoalesce(this.storage.getItem(this.key), () => ( null));
if (val === null) {
return _nullishCoalesce(defaultVal, () => ( null));
}
return JSON.parse(val);
}
/**
* 删除值
*/
removeItem() {
this.value = null;
this.storage.removeItem(this.key);
}
/**
* 更新值
*/
updateItem(val) {
this.value = null;
const oldVal = this.getItem();
if (_chunk5PB5B4HHcjs.isArray.call(void 0, val) && _chunk5PB5B4HHcjs.isArray.call(void 0, oldVal)) {
val = [...oldVal, ...val];
} else if (_chunkOSEQ7XR6cjs.isObject.call(void 0, val) && _chunkOSEQ7XR6cjs.isObject.call(void 0, 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}: \u547D\u4E2D\u7F13\u5B58\uFF01`);
return this.value;
}
this._debug(`${this.key}: \u8BFB\u53D6\u5B58\u50A8\uFF01`);
const val = this.getItem();
if (val === null) {
return _nullishCoalesce(defaultVal, () => ( null));
}
this.value = val;
return this.value;
}
/**
* 清除缓存
*/
clearCache() {
this.value = null;
}
}, _class);
exports.Storage = Storage;