localStorage设置过期时间

export function getItemKeyList(): Array<string> {
  const keyList = [];
  for (let i = 0; i < localStorage.length; i += 1) {
    const key = localStorage.key(i);
    if (key) {
      keyList.push(`${key}`);
    }
  }
  return keyList;
}

export function clearExpiredKeys() {
  const keyList = getItemKeyList();
  keyList.forEach(key => {
    const match = key.match(/\|\|\|(\d{13})$/);
    if (match) {
      // const uselessPart = match[0];
      const expiresAt = Number(match[1]);
      if (new Date().getTime() > expiresAt) {
        localStorage.removeItem(key);
      }
    }
  });
}

function clearKeysOf(unwrappedKey: string) {
  const keyList = getItemKeyList();
  const regExp = new RegExp(`${unwrappedKey}\\|\\|\\|`);
  keyList.forEach(fullKey => {
    if (regExp.test(fullKey)) {
      localStorage.removeItem(fullKey);
    }
  });
}

function getTargetFullKey(unwrappedKey: string): string {
  const keyList = getItemKeyList();
  let result = '';
  keyList.forEach(fullKey => {
    const regExp = new RegExp(`^${unwrappedKey}\\|\\|\\|`);
    if (
      regExp.test(fullKey)
    ) {
      result = fullKey;
    }
  });
  return result;
}

export function setItem(options: {
  key: string;
  value: string;
  expiresAt?: number;
}): void {
  clearExpiredKeys();
  clearKeysOf(options.key);

  let expiresAtString = '';
  if (options.expiresAt) {
    expiresAtString = `${options.expiresAt}`;
    if (expiresAtString.length !== 13) {
      throw new Error(`Invalid expiresAt value: ${expiresAtString}`);
    }
  }

  const fullKey = `${options.key}|||${expiresAtString}`;
  localStorage.setItem(fullKey, options.value);
}

export function getItem(unwrappedKey: string): string|null {
  clearExpiredKeys();
  const targetFullKey = getTargetFullKey(unwrappedKey);
  return localStorage.getItem(targetFullKey);
}

export function removeItem(unwrappedKey: string): void {
  clearExpiredKeys();
  const targetFullKey = getTargetFullKey(unwrappedKey);
  localStorage.removeItem(targetFullKey);
}

  

上一篇:使用浏览器的 Local Storage 真的安全吗?


下一篇:[javascript] 简单封装localStorge操作