UNPKG

@yangshuanlin/y-cache

Version:

加密缓存插件,支持set,get,del,tag,只调试过vue

117 lines (114 loc) 2.93 kB
import sha256 from 'crypto-js/sha256' import AES from 'crypto-js/aes' import md5 from 'crypto-js/md5' import CryptoJS from 'crypto-js' const Cache = { /** * 标签分组名称 */ tagName: null, /** * 从缓存获取数据 * @param {string} key * @returns */ get: function(key) { key = this.getKey(key) let value = localStorage.getItem(key) if (value) { value = this.decryptValue(key, value) if (value.l === 0) { return value.d } else { if (value.l >= this.getNow()) { return value.d } else { return null } } } else { return value } }, /** * 存 * @param {string} key * @param {object|id|string} value * @param {int} ttl */ set: function(key, value, ttl = 0) { const limitTime = this.getLimitTime(ttl) key = this.getKey(key) this.setTag(key) value = { 'd': value, 'l': limitTime } value = this.cryptValue(value, key) localStorage.setItem(key, value) }, // 删除 del: function(key) { key = this.getKey(key) localStorage.removeItem(key) }, // 分组 tag: function(tagName) { this.tagName = tagName return this }, setTag: function(key) { if (this.tagName !== null) { const tagNameKey = this.getKey(this.tagName) let tagValue = localStorage.getItem(tagNameKey) if (tagValue) { tagValue = JSON.parse(tagValue) } else { tagValue = [] } tagValue.push(key) localStorage.setItem(tagNameKey, JSON.stringify(tagValue)) } }, clear: function(tagName) { const tagNameKey = this.getKey(tagName) let tagValue = localStorage.getItem(tagNameKey) if (tagValue) { tagValue = JSON.parse(tagValue) tagValue.map((v) => { localStorage.removeItem(v) }) localStorage.removeItem(tagNameKey) } }, clearAll: function() { localStorage.clear() }, // 获取当前时间戳 getLimitTime: function(ttl) { if (ttl === 0) { return 0 } else { return new Date().getTime() + ttl * 1000 } }, getNow: function() { return new Date().getTime() }, // key处理 getKey: function(key) { return md5(key).toString() }, cryptValue: function(value, key) { value = JSON.stringify(value) const keyAndIv = this.getAesKeyAndIv(key) return AES.encrypt(value, keyAndIv.key).toString() }, decryptValue: function(key, value) { const keyAndIv = this.getAesKeyAndIv(key) const str = AES.decrypt(value, keyAndIv.key).toString(CryptoJS.enc.Utf8) return JSON.parse(str) }, getAesKeyAndIv: function(key) { const str = sha256(key).toString() return { 'key': str.substr(0, 16), 'iv': str.substr(50, 16) } } } export default Cache