工具函数 Utils-1

文章介绍了使用JavaScript的Crypto-js库进行数据加密(AES加密/解密)的方法,以及如何通过setCookie和getCookie函数进行安全的客户端存储。同时,还提及了`firstAsyncFetch`函数用于处理首次请求加载,管理加密数据和Cookie的生命周期。
摘要由CSDN通过智能技术生成

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();
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值