Carson
2021-11-24 dc4b05272f67b5ea8a85cac15b11e14a76c2c1d6
提交 | 用户 | age
234c1d 1 import { cacheCipher } from '/@/settings/encryptionSetting';
fcee7d 2 import type { EncryptionParams } from '/@/utils/cipher';
V 3 import { AesEncryption } from '/@/utils/cipher';
ec7bef 4 import { isNullOrUnDef } from '/@/utils/is';
V 5
234c1d 6 export interface CreateStorageParams extends EncryptionParams {
bba776 7   prefixKey: string;
234c1d 8   storage: Storage;
V 9   hasEncrypt: boolean;
bba776 10   timeout?: Nullable<number>;
234c1d 11 }
V 12 export const createStorage = ({
13   prefixKey = '',
14   storage = sessionStorage,
15   key = cacheCipher.key,
16   iv = cacheCipher.iv,
bba776 17   timeout = null,
234c1d 18   hasEncrypt = true,
bba776 19 }: Partial<CreateStorageParams> = {}) => {
234c1d 20   if (hasEncrypt && [key.length, iv.length].some((item) => item !== 16)) {
V 21     throw new Error('When hasEncrypt is true, the key or iv must be 16 bits!');
22   }
23
fcee7d 24   const encryption = new AesEncryption({ key, iv });
234c1d 25
V 26   /**
dc4b05 27    * Cache class
C 28    * Construction parameters can be passed into sessionStorage, localStorage,
234c1d 29    * @class Cache
V 30    * @example
31    */
32   const WebStorage = class WebStorage {
33     private storage: Storage;
34     private prefixKey?: string;
fcee7d 35     private encryption: AesEncryption;
234c1d 36     private hasEncrypt: boolean;
V 37     /**
38      *
39      * @param {*} storage
40      */
41     constructor() {
42       this.storage = storage;
43       this.prefixKey = prefixKey;
44       this.encryption = encryption;
45       this.hasEncrypt = hasEncrypt;
46     }
47
48     private getKey(key: string) {
49       return `${this.prefixKey}${key}`.toUpperCase();
50     }
51
52     /**
dc4b05 53      * Set cache
234c1d 54      * @param {string} key
V 55      * @param {*} value
dc4b05 56      * @param {*} expire Expiration time in seconds
234c1d 57      * @memberof Cache
V 58      */
bba776 59     set(key: string, value: any, expire: number | null = timeout) {
234c1d 60       const stringData = JSON.stringify({
V 61         value,
ec7bef 62         time: Date.now(),
V 63         expire: !isNullOrUnDef(expire) ? new Date().getTime() + expire * 1000 : null,
234c1d 64       });
V 65       const stringifyValue = this.hasEncrypt
66         ? this.encryption.encryptByAES(stringData)
67         : stringData;
68       this.storage.setItem(this.getKey(key), stringifyValue);
69     }
70
71     /**
dc4b05 72      * Read cache
234c1d 73      * @param {string} key
dc4b05 74      * @param {*} def
234c1d 75      * @memberof Cache
V 76      */
77     get(key: string, def: any = null): any {
ec7bef 78       const val = this.storage.getItem(this.getKey(key));
V 79       if (!val) return def;
80
81       try {
82         const decVal = this.hasEncrypt ? this.encryption.decryptByAES(val) : val;
83         const data = JSON.parse(decVal);
84         const { value, expire } = data;
85         if (isNullOrUnDef(expire) || expire >= new Date().getTime()) {
86           return value;
234c1d 87         }
ec7bef 88         this.remove(key);
V 89       } catch (e) {
90         return def;
234c1d 91       }
V 92     }
93
94     /**
95      * Delete cache based on key
96      * @param {string} key
97      * @memberof Cache
98      */
99     remove(key: string) {
100       this.storage.removeItem(this.getKey(key));
101     }
102
103     /**
104      * Delete all caches of this instance
105      */
106     clear(): void {
107       this.storage.clear();
108     }
109   };
110   return new WebStorage();
111 };