如何封装一个前端持久化函数

96 阅读1分钟

class StorageFactory {
  constructor(storageType) {
    this.storage = storageType === 'local'? localStorage : sessionStorage;
    this.prefix = storageType === 'local'? 'LS_' : 'SS_';
  }

  setItem(key, value, expirationMinutes = null) {
    let encryptedValue;
    if (expirationMinutes!== null) {
      const expirationTimestamp = Date.now() + expirationMinutes * 60 * 1000;
      encryptedValue = this.encrypt(`${value}|${expirationTimestamp}`);
    } else {
      encryptedValue = this.encrypt(value);
    }
    this.storage.setItem(`${this.prefix}${key}`, encryptedValue);
  }

  getItem(key) {
    const encryptedValue = this.storage.getItem(`${this.prefix}${key}`);
    if (!encryptedValue) return null;
    const decryptedValue = this.decrypt(encryptedValue);
    if (!decryptedValue.includes('|')) return decryptedValue;
    const [value, expirationTimestamp] = decryptedValue.split('|');
    if (expirationTimestamp && Date.now() > parseInt(expirationTimestamp)) {
      this.removeItem(key);
      return null;
    }
    return value;
  }

  removeItem(key) {
    this.storage.removeItem(`${this.prefix}${key}`);
  }

  clear() {
    for (let i = 0; i < this.storage.length; i++) {
      const key = this.storage.key(i);
      if (key.startsWith(this.prefix)) {
        this.storage.removeItem(key);
      }
    }
  }

  encrypt(value) {
    let encryptedValue = '';
    for (let i = 0; i < value.length; i++) {
      encryptedValue += String.fromCharCode(value.charCodeAt(i) + 1);
    }
    return btoa(encryptedValue);
  }

  decrypt(encryptedValue) {
    let decryptedValue = '';
    const value = atob(encryptedValue);
    for (let i = 0; i < value.length; i++) {
      decryptedValue += String.fromCharCode(value.charCodeAt(i) - 1);
    }
    return decryptedValue;
  }
}

const createStorage = (storageType) => new StorageFactory(storageType);

export const localStorageUtil = createStorage('local');
export const sessionStorageUtil = createStorage('session');

使用

// 设置 local storage
localStorageUtil.setItem('userName', '张三', 30); // 设置超时时间为 30 分钟
// 获取 local storage
const userName = localStorageUtil.getItem('userName');
console.log(userName);
// 删除 local storage
localStorageUtil.removeItem('userName');

// 设置 session storage
sessionStorageUtil.setItem('token', '123456');
// 获取 session storage
const token = sessionStorageUtil.getItem('token');
console.log(token);
// 删除 session storage
sessionStorageUtil.removeItem('token');