54 lines
1.2 KiB
TypeScript
54 lines
1.2 KiB
TypeScript
import CryptoJS from 'crypto-js';
|
|
|
|
const tools = {
|
|
data: {
|
|
set(cacheKey, data, expireIn = 0) {
|
|
let cacheValue = {
|
|
content: data,
|
|
expireIn: expireIn === 0 ? 0 : new Date().getTime() + expireIn * 1000
|
|
}
|
|
return localStorage.setItem(cacheKey, tools.base64.encrypt(JSON.stringify(cacheValue)))
|
|
},
|
|
get(cacheKey) {
|
|
try {
|
|
const cacheValue = JSON.parse(tools.base64.decrypt(localStorage.getItem(cacheKey)))
|
|
if (cacheValue) {
|
|
let nowTime = new Date().getTime()
|
|
if (nowTime > cacheValue.expireIn && cacheValue.expireIn !== 0) {
|
|
localStorage.removeItem(cacheKey)
|
|
return null;
|
|
}
|
|
return cacheValue.content
|
|
}
|
|
return null
|
|
} catch (err) {
|
|
return null
|
|
}
|
|
},
|
|
remove(cacheKey) {
|
|
return localStorage.removeItem(cacheKey)
|
|
},
|
|
clear() {
|
|
return localStorage.clear()
|
|
}
|
|
},
|
|
base64: {
|
|
encrypt(data) {
|
|
return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
|
|
},
|
|
decrypt(cipher) {
|
|
return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8)
|
|
}
|
|
},
|
|
go: async function (fn: Function) {
|
|
try {
|
|
let res = await fn
|
|
return [res, null]
|
|
} catch (err) {
|
|
return [null, err]
|
|
}
|
|
}
|
|
}
|
|
|
|
export default tools
|