typescript LocalStorage服务

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript LocalStorage服务相关的知识,希望对你有一定的参考价值。

import { Injectable } from '@angular/core';

// https://github.com/RonenNess/ExpiredStorage
@Injectable()
export class ExpiredStorageService {

  readonly storage = localStorage;

  private expiration_key_prefix = '__expired_storage_timestamp__';



  /**
   * Get current timestamp in seconds.
   **/
  private static getTimestamp() {
    return Math.floor(((new Date).getTime()) / 1000);
  }

  /**
   * Set item.
   * @param key: Item key to set (string).
   * @param value: Value to store (string).
   * @param expiration: Expiration time, in seconds. If not provided, will not set expiration time.
   * @param return: Storage.setItem() return code.
   **/
  public setItem(key, value, expiration) {

    // set item
    const item = this.storage.setItem(key, value);

    // set expiration timestamp (only if defined)
    if (expiration) {
      this.updateExpiration(key, expiration);
    }

    // return set value return value
    return item;
  }

  /**
   * Get item.
   * @param key: Item key to get (string).
   * @return: Stored value, or undefined if not set / expired.
   */
  public getItem(key: string) {

    // if expired remove item and return null
    if (this.isExpired(key)) {
      this.removeItem(key);
      return null;
    }

    // try to fetch and return item value
    return this.storage.getItem(key);
  }

  /**
   * Get item + metadata such as time left and if expired.
   * Even if item expired, will not remove it.
   * @param key: Item key to get (string).
   * @return: Dictionary with: {value, timeLeft, isExpired}
   */
  public peek(key) {

    // get value and time left
    const ret = {
      value: this.storage.getItem(key),
      timeLeft: this.getTimeLeft(key),
      isExpired: null
    };

    // set if expired
    ret.isExpired = ret.timeLeft !== null && ret.timeLeft <= 0;

    // return data
    return ret;
  }


  /**
   * Get item time left to live.
   * @param key: Item key to get (string).
   * @return: Time left to expire (in seconds), or null if don't have expiration date.
   */
  private getTimeLeft(key) {

    // try to fetch expiration time for key
    const expireTime = parseInt(this.storage.getItem(this.expiration_key_prefix + key), 10);

    // if got expiration time return how much left to live
    if (expireTime && !isNaN(expireTime)) {

      return expireTime - ExpiredStorageService.getTimestamp();
    }

    // if don't have expiration time return null
    return null;
  }

  /**
   * Return if an item is expired (don't remove it, even if expired).
   * @param key: Item key to check (string).
   * @return: True if expired, False otherwise.
   */
  public isExpired(key) {

    // get time left for item
    const timeLeft = this.getTimeLeft(key);

    // return if expired
    return timeLeft !== null && timeLeft <= 0;
  }

  /**
   * Update expiration time for an item (note: doesn't validate that the item is set).
   * @param key: Item key to update expiration for (string).
   * @param expiration: New expiration time in seconds to set.
   * @return: Storage.setItem() return code for setting new expiration.
   **/
  public updateExpiration(key, expiration) {
    return this.storage.setItem(this.expiration_key_prefix + key, ExpiredStorageService.getTimestamp() + expiration);
  }

  /**
   * Remove an item.
   * @param key: Item key to remove (string).
   * @return: Storage.removeItem() return code.
   */
  public removeItem(key) {

    // remove the item itself and its expiration time
    const ret = this.storage.removeItem(key);
    this.storage.removeItem(this.expiration_key_prefix + key);

    // return optional return code
    return ret;
  }

  /**
   * Set a json serializable value. This basically calls JSON.stringify on 'val' before setting it.
   * @param key: Item key to set (string).
   * @param value: Value to store (object, will be stringified).
   * @param expiration: Expiration time, in seconds. If not provided, will not set expiration time.
   * @param return: Storage.setItem() return code.
   **/
  public setJson(key, val, expiration) {
    // special case - make sure not undefined, because it would just write "undefined" and crash on reading.
    if (val === undefined) {
      throw new Error('Cannot set undefined value as JSON!');
    }

    // set stringified value
    return this.setItem(key, JSON.stringify(val), expiration);
  }

  /**
   * Get a json serializable value. This basically calls JSON.parse on the returned value.
   * @param key: Item key to get (string).
   * @return: Stored value, or undefined if not set / expired.
   **/
  public getJson(key) {
    // get value
    const val = this.getItem(key);

    // if null, return null
    if (val === null) {
      return null;
    }

    // parse and return value
    return JSON.parse(val);
  }

  /**
   * Get all keys in storage, not including internal keys used to store expiration.
   * @param: includeExpired: if true, will also include expired keys.
   * @return: Array with keys.
   */
  public keys(includeExpired) {
    // create list to return
    const ret = [];

    // iterate over storage keys to find all non-expiration keys
    this.iterKeys((storageKey) => {

      // if its not a timestamp key, skip it
      if (storageKey.indexOf(this.expiration_key_prefix) !== 0) {

        // add to return list, but only if including expired keys or if not expired yet
        if (includeExpired || !this.isExpired(storageKey)) {
          ret.push(storageKey);
        }
      }
    });

    // return keys
    return ret;
  }

  /**
   * Clear the entire storage and all keys in it.
   */
  public clear() {
    this.storage.clear();
  }

  /**
   * Clear expired keys.
   * If you never call this function, expired keys will remain until you try to get them / reset a new value.
   *
   * @param return: List of removed keys due to expiration.
   */
  public clearExpired() {

    // return list
    const ret = [];

    // iterate over storage keys to find all counters
    this.iterKeys((storageKey) => {

      // if its not a timestamp key, skip it
      if (storageKey.indexOf(this.expiration_key_prefix) === 0) {

        // get item key
        const itemKey = storageKey.substr(this.expiration_key_prefix.length);

        // if expired remove it + the item
        if (this.isExpired(itemKey)) {

          this.removeItem(itemKey);
          ret.push(itemKey);
        }
      }
    });

    // return list with removed keys
    return ret;
  }

  /**
   * Iterate all keys in storage class.
   * @param callback: Function to call for every key, with a single param: key.
   */
  private iterKeys(callback) {

    // first check if storage define a 'keys()' function. if it does, use it
    if (typeof this.storage.keys === 'function') {
      const keys = this.storage.keys();
      for (let i = 0; i < keys.length; ++i) {
        callback(keys[i]);
      }
    } else if (typeof Object === 'function' && Object.keys) {
      // if not supported try to use object.keys
      const keys = Object.keys(this.storage);
      for (let i = 0; i < keys.length; ++i) {
        callback(keys[i]);
      }
    } else if (this.storage.length !== undefined && typeof this.storage.key === 'function') {
      // if not supported try to use iteration via length

      // first build keys array, so this function will be delete-safe
      // (eg if callback remove keys it won't cause problems due to index change)
      const keys = [];
      for (let i = 0, len = this.storage.length; i < len; ++i) {
        keys.push(this.storage.key(i));
      }
      // now actually iterate keys
      for (let i = 0; i < keys.length; ++i) {
        callback(keys[i]);
      }
    } else {
      // if both methods above didn't work, iterate on all keys in storage class hoping for the best..
      for (const storageKey of Object.keys(this.storage)) {
        callback(storageKey);
      }
    }
  }
}



以上是关于typescript LocalStorage服务的主要内容,如果未能解决你的问题,请参考以下文章

HTML5 localStorage 有用的函数 // JavaScript,TypeScript [关闭]

从 localStorage Typescript/JavaScript 中提取用户名

Redux-localstorage 的 TypeScript 打字问题,persistState 不是一个函数

typescript Angular Service将FormGroup与LocalStorage同步(获取和设置)

刷新浏览器后显示 localStorage 中的收藏项 - Next.js 和 Typescript 项目

typescript 使用数组和localstorage来保存我们的应用程序中的捕获