@10yun/cv-js-utils
Version:
常用 js-utils 工具类库
234 lines (227 loc) • 6.34 kB
JavaScript
// import { deCrypto, enCrypto } from './crypto/index.js';
/**
* 将一个 JSON 字符串转换为对象(已try)
* @param str
* @param defaultVal
* @return {*}
*/
function __cc_jsonParse(str, defaultVal = undefined) {
if (str === null) {
// return defaultVal ? defaultVal : {};
return defaultVal ? defaultVal : '';
}
if (typeof str === 'object') {
return str;
}
try {
return JSON.parse(str.replace(/\n/g, '\\n').replace(/\r/g, '\\r'));
} catch (e) {
// return defaultVal ? defaultVal : {};
return defaultVal ? defaultVal : '';
}
}
/**
* 默认7天
*/
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;
/**
* 参数存储,缓存
* @type {{set(*, *): void, get(*): *, del(*): void, clear(): void}}
*/
class StorageClass {
constructor(options) {
// 缓存前缀
this.prefix = options.prefix || '';
// 缓存时间
this.expired = options.expired || DEFAULT_CACHE_TIME;
// 是否加密
this.crypto = options.crypto ? true : false;
// 是否合并
this.merge = options.merge ? true : false;
/**
* 缓存的key
*/
this.keyExpired = {
session: {},
local: {}
};
this.keyGroup = {
session: [],
local: []
};
}
/**
* 判断key是否过期
*/
_checkExpiredKey(type, key) {
if (type && (type == 'session' || type == 'local')) {
const expire = this.keyExpired[type][key];
if (expire >= Date.now()) {
return true;
}
}
return false;
}
_encodeData() {
// var tempParamObj = JSON.parse(window.localStorage.getItem('cache_api_store'));
// tempParamObj[key] = value;
// window.localStorage.setItem('cache_api_store', JSON.stringify(tempParamObj));
}
_decodeData() {}
_settKey(type, key, expired) {
if (type && (type == 'session' || type == 'local')) {
this.keyExpired[type][key] = expired || this.expired;
// this.expired !== null ? new Date().getTime() + this.expired * 1000 : null
this.keyGroup[type].push(key);
}
}
_deleteKey(type, key) {
if (type && (type == 'session' || type == 'local')) {
if (key) {
delete this.keyExpired[type][key];
this.keyGroup[type] = this.keyGroup[type].filter((item) => item !== key);
} else {
this.keyExpired[type] = {};
this.keyGroup[type] = [];
}
}
}
/**
* -------------------------------------------------------会话存储------------------------------------
* 会话存储-存
* @param {*} key 键名
* @param {*} value 值
*/
sessionSet(key, oldData, expired) {
let newData = JSON.stringify(oldData);
// if (history.hasOwnProperty(key) && key !== '::count') {
// let history = JSON.parse(window.sessionStorage['__history__'] || '{}');
sessionStorage.setItem(key, newData);
this._settKey('session', key, expired);
}
/**
* 会话存储-取
* @param {*} key 键名
*/
sessionGet(key) {
let _data = sessionStorage.getItem(key);
try {
return JSON.parse(_data);
// return __cc_jsonParse(_data);
} catch (e) {
return _data;
}
}
/**
* 会话存储-删
* @param {*} key 键名
*/
sessionDel(key) {
if (!window.sessionStorage) return false;
sessionStorage.removeItem(key);
this._deleteKey('session', key);
}
/**
* 删除sessionStorage
* 会话存储-删处全部
*/
sessionClear() {
if (!window.sessionStorage) return false;
sessionStorage.clear();
for (let i in this.keyGroup['session']) {
sessionStorage.removeItem(i);
}
this._deleteKey('session');
}
/**
* -------------------------------------------------------永久存储-----------------------------------
* 永久存储-存
* @param {*} key 键名
* @param {*} value 值
*/
/**
* @description localStorage set
* @param {String|int} key 只支持 字符串和数字
* @param {Mixid} val 支持除了Function和Symbol的所有数据类型
* @param {int} expired 缓存秒
*/
localSet(key, value, expired) {
// 判断是否支持或开启localStorage
// 无痕模式下和ie安全模式下localStorage会被禁用
if (!window.localStorage) {
console.warn('浏览器不支持localStorage');
return;
}
if (value === '' || value === null || value === undefined) {
value = null;
}
/**
* 是否合并覆盖
* 默认: 覆盖
*/
// if (localStorage.hasOwnProperty(key)) {
// let old_value = JSON.parse(localStorage.getItem(key));
// value = Object.assign(old_value, value);
// }
/**
* 是否加密
*/
// const last_value = this.crypto ? enCrypto(value) : JSON.stringify(value);
const last_value = typeof value == 'string' ? value : JSON.stringify(value);
window.localStorage.setItem(key, last_value);
this._settKey('local', key, expired);
}
/**
* 永久存储-取
* @param {*} key 键名
*/
localGet(key) {
if (!window.localStorage) {
console.warn('浏览器不支持localStorage');
return;
}
this._checkExpiredKey('local', key);
// if (window.localStorage.hasOwnProperty(key)) {
// return JSON.parse(localStorage.getItem(key));
// } else {
// return false;
// }
let _data = window.localStorage.getItem(key);
try {
/**
* 是否加密
*/
// storageData = crypto ? deCrypto(json) : JSON.parse(json);
if (Object.keys(_data).length == 0 || JSON.stringify(_data) == '{}') {
_data = '';
} else {
// 取缓存,如果解析出来的是对象, 则返回对象
_data = JSON.parse(_data);
// _data = __cc_jsonParse(_data);
}
} catch (e) {
// console.warn("val不是对象或者数组");
}
return _data;
}
/**
* 永久存储-删
* @description 移除某一个key的storage
* @param {*} key 键名
*/
localDel(key) {
if (!window.localStorage) return false;
window.localStorage.removeItem(key);
this._deleteKey('local', key);
}
// 清空
localClear() {
if (!window.localStorage) return false;
window.localStorage.clear();
for (let i in this.keyGroup['local']) {
window.localStorage.removeItem(i);
}
this._deleteKey('local');
}
}
export default StorageClass;