@daysnap/utils
Version:
68 lines (65 loc) • 1.32 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;
constructor(key, storage) {
this.key = key;
this.storage = storage;
}
/**
* 设置值
*/
setItem(val) {
this.value = null;
this.storage.setItem(this.key, JSON.stringify(val));
return val;
}
getItem(defaultVal) {
const val = this.storage.getItem(this.key);
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.storage.getItem(this.key);
if (val === null) {
return defaultVal ?? null;
}
this.removeItem();
return JSON.parse(val);
}
getItemWithCache(defaultVal) {
return this.value ?? (this.value = this.getItem(defaultVal));
}
};
export {
Storage
};