@ryanuo/utils
Version:
提供多种实用工具函数,涵盖算法、浏览器操作、网络请求等多个领域
74 lines (73 loc) • 1.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.safeStorage = void 0;
var _common = require("../common");
function getStorage(type = "local") {
return type === "local" ? localStorage : sessionStorage;
}
function withExpiration(value, expires) {
if (!expires) return value;
const now = (/* @__PURE__ */new Date()).getTime();
const item = {
value,
expires: now + expires
};
return item;
}
function checkExpiration(item) {
if (!item || typeof item !== "object") return item;
if ("expires" in item && "value" in item) {
const now = (/* @__PURE__ */new Date()).getTime();
if (now > item.expires) return null;
return item.value;
}
return item;
}
const safeStorage = exports.safeStorage = {
get(key, options = {}) {
try {
const {
storage = "local"
} = options;
const selectedStorage = getStorage(storage);
const data = selectedStorage.getItem(key);
if (!data) return null;
const parsed = (0, _common.safeJSONParse)(data);
const result = checkExpiration(parsed);
if (result === null) selectedStorage.removeItem(key);
return result;
} catch {
return null;
}
},
set(key, value, options = {}) {
try {
const {
storage = "local",
expires
} = options;
const selectedStorage = getStorage(storage);
const item = withExpiration(value, expires);
selectedStorage.setItem(key, JSON.stringify(item));
return true;
} catch {
return false;
}
},
remove(key, options = {}) {
const {
storage = "local"
} = options;
const selectedStorage = getStorage(storage);
selectedStorage.removeItem(key);
},
clear(options = {}) {
const {
storage = "local"
} = options;
const selectedStorage = getStorage(storage);
selectedStorage.clear();
}
};