1. 存储数据加密处理
import Crypto from 'crypto-js';
type C_TYPE<T> = string | number | boolean | T[] | Record<string | number, T>;
type S_TYPE<T> = {
current: number;
value: C_TYPE<T>;
expires: number;
};
const SaltVal = Crypto.enc.Utf8.parse('QWER');
export function encrypt(value: string) {
return Crypto.AES.encrypt(value, SaltVal, {
mode: Crypto.mode.ECB,
padding: Crypto.pad.Pkcs7,
}).toString();
}
export function decrypt(value: string) {
return Crypto.AES.decrypt(value, SaltVal, {
mode: Crypto.mode.ECB,
padding: Crypto.pad.Pkcs7,
}).toString(Crypto.enc.Utf8);
}
function filterEncrypt<T>(value: S_TYPE<T>) {
return encrypt(JSON.stringify(value));
}
function revert(value: string) {
try {
const locals = decrypt(value);
const now = Date.now();
const json = JSON.parse(locals);
const { current = 0, expires = 0 } = json;
if (now <= current + expires) {
return json.value;
}
} catch (error) {
console.error(error);
}
}
export function setCookie<T>(
key: string,
value: C_TYPE<T>,
expires = 86400000
) {
const locals = filterEncrypt({
expires,
value,
current: Date.now(),
});
localStorage.setItem(key, locals);
}
export function getCookie(key: string) {
const locals = localStorage.getItem(key);
return locals ? revert(locals) : null;
}
2. 首次请求加载函数
const createFirstAsyncFetch = () => {
let S_Q: Set<string> = new Set();
let E_K_V: null | string = null;
async function firstAsyncFetch<T = any, R = any>(
key: string,
request: (data?: T) => Promise<R>,
params?: T
): Promise<undefined | R> {
if (S_Q.has(key)) {
return getCookie(key);
}
if (typeof request === 'function') {
try {
Reflect.set(request, '_key_', key);
const data = await request(params);
E_K_V = key;
if (data) S_Q.add(key);
return data;
} catch (error) {
S_Q.delete(key);
}
}
}
firstAsyncFetch.showKey = () => {
return E_K_V;
};
firstAsyncFetch.setCookie = (value: any) => {
if (E_K_V) setCookie<any>(E_K_V, value);
};
firstAsyncFetch.clearItems = () => {
for (const key of S_Q) {
localStorage.removeItem(key);
}
S_Q = new Set();
};
firstAsyncFetch.removeItem = (key: string) => {
S_Q.delete(key);
localStorage.removeItem(key);
};
return firstAsyncFetch;
};
export const firstAsyncFetch = createFirstAsyncFetch();