|
| 1 | +/* |
| 2 | + * @Author: Chacha |
| 3 | + * @Date: 2022年05月29日 11:19:24 |
| 4 | + * @Last Modified by: Chacha |
| 5 | + * @Last Modified time: 2022年05月29日 13:18:34 |
| 6 | + */ |
| 7 | + |
| 8 | +/** |
| 9 | + * Expire storage,支持过期时间的 localStorage |
| 10 | + */ |
| 11 | + |
| 12 | +class ExpireStorage { |
| 13 | + prefix = "Chacha"; |
| 14 | + |
| 15 | + tag = "|Chacha|"; |
| 16 | + |
| 17 | + defaultTime = Date.now() + 24 * 60 * 60 * 31 * 1000; // 默认时长1个月 |
| 18 | + |
| 19 | + constructor(prefix, tag) { |
| 20 | + this.prefix = prefix; |
| 21 | + this.tag = tag; |
| 22 | + } |
| 23 | + |
| 24 | + setItem(key, value, time) { |
| 25 | + key = `${this.prefix}${key}`; |
| 26 | + time = time ? new Date(time).getTime() : this.defaultTime; |
| 27 | + |
| 28 | + // 构造一个形如 1646094676134|Chacha|"Hello World" 结构的字符串 |
| 29 | + window.localStorage.setItem( |
| 30 | + key, |
| 31 | + `${time}${this.tag}${JSON.stringify(value)}` |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + getItem(key) { |
| 36 | + key = `${this.prefix}${key}`; |
| 37 | + let value = window.localStorage.getItem(key); |
| 38 | + |
| 39 | + if (value) { |
| 40 | + let index = value.indexOf(this.tag); |
| 41 | + let time = +value.slice(0, index); |
| 42 | + |
| 43 | + // 判断时间是否已过期 |
| 44 | + if (time > Date.now()) { |
| 45 | + value = JSON.parse(value.slice(index + this.tag.length)); |
| 46 | + } else { |
| 47 | + value = null; |
| 48 | + window.localStorage.removeItem(key); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return value; |
| 53 | + } |
| 54 | +} |
0 commit comments