fix: ensure that storage is deleted correctly close #292

This commit is contained in:
Vben
2021-02-26 20:21:13 +08:00
parent efb27aff0a
commit ec7bef792b
3 changed files with 37 additions and 30 deletions

View File

@@ -4,6 +4,8 @@ import type { EncryptionParams } from '/@/utils/cipher';
import { AesEncryption } from '/@/utils/cipher';
import { isNullOrUnDef } from '/@/utils/is';
export interface CreateStorageParams extends EncryptionParams {
prefixKey: string;
storage: Storage;
@@ -61,7 +63,8 @@ export const createStorage = ({
set(key: string, value: any, expire: number | null = timeout) {
const stringData = JSON.stringify({
value,
expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
time: Date.now(),
expire: !isNullOrUnDef(expire) ? new Date().getTime() + expire * 1000 : null,
});
const stringifyValue = this.hasEncrypt
? this.encryption.encryptByAES(stringData)
@@ -75,21 +78,20 @@ export const createStorage = ({
* @memberof Cache
*/
get(key: string, def: any = null): any {
const item = this.storage.getItem(this.getKey(key));
if (item) {
try {
const decItem = this.hasEncrypt ? this.encryption.decryptByAES(item) : item;
const data = JSON.parse(decItem);
const { value, expire } = data;
if (expire === null || expire >= new Date().getTime()) {
return value;
}
this.remove(this.getKey(key));
} catch (e) {
return def;
const val = this.storage.getItem(this.getKey(key));
if (!val) return def;
try {
const decVal = this.hasEncrypt ? this.encryption.decryptByAES(val) : val;
const data = JSON.parse(decVal);
const { value, expire } = data;
if (isNullOrUnDef(expire) || expire >= new Date().getTime()) {
return value;
}
this.remove(key);
} catch (e) {
return def;
}
return def;
}
/**