@daysnap/utils
Version:
96 lines (93 loc) • 1.99 kB
JavaScript
import {
isArray
} from "./chunk-CSZ7G34M.js";
import {
isObject
} from "./chunk-XCSSSEK2.js";
// src/storage/storage.ts
var Storage = class {
key;
storage;
value = null;
options = { debug: false, cached: false };
constructor(key, storage, options) {
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 = this.storage.getItem(this.key) ?? null;
if (val === null) {
return 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 (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}: \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 defaultVal ?? null;
}
this.value = val;
return this.value;
}
/**
* 清除缓存
*/
clearCache() {
this.value = null;
}
};
export {
Storage
};