cache.js
2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const __DEBUG__ = process.env.NODE_ENV !== 'production';
/**
* 缓存数据优化
* import cache from '@/utils/cache'
* 使用方法 【
* 一、设置缓存
* string cache.put('k', 'string你好啊');
* json cache.put('k', { "b": "3" }, 2);
* array cache.put('k', [1, 2, 3]);
* boolean cache.put('k', true);
* 二、读取缓存
* 默认值 cache.get('k')
* string cache.get('k', '你好')
* json cache.get('k', { "a": "1" })
* 三、移除/清理
* 移除: cache.remove('k');
* 清理:cache.clear();
* 】
* @type {String}
*/
const prefix = __DEBUG__ ? 'EAGLE_DEV_' : 'EAGLE_'; // 缓存前缀
const postfix = '_SEED';
/**
* 设置缓存
* @param {[type]} k [键名]
* @param {[type]} v [键值]
* @param {[type]} t [时间、单位秒]
*/
function put(k, v, t) {
localStorage.setItem(prefix + k, JSON.stringify(v));
var seconds = parseInt(t);
if (seconds > 0) {
var timestamp = Date.parse(new Date());
timestamp = timestamp / 1000 + seconds;
localStorage.setItem(prefix + k + postfix, JSON.stringify(timestamp));
} else {
localStorage.removeItem(prefix + k + postfix);
}
}
/**
* 获取缓存
* @param {[type]} k [键名]
* @param {[type]} def [获取为空时默认]
*/
function get(k, def) {
var deadtime = parseInt(localStorage.getItem(prefix + k + postfix));
if (deadtime) {
if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
if (def) {
return def;
} else {
return false;
}
}
}
var res = localStorage.getItem(prefix + k);
if (res) {
return JSON.parse(res);
} else {
if (def == undefined || def == '') {
def = false;
}
return def;
}
}
function remove(k) {
localStorage.removeItem(prefix + k);
localStorage.removeItem(prefix + k + postfix);
}
/**
* 清理所有缓存
* @return {[type]} [description]
*/
function clear() {
localStorage.clear();
}
module.exports = {
put: put,
get: get,
remove: remove,
clear: clear,
};