All files / src/cache cache-session-storage.ts

92.85% Statements 13/14
100% Branches 2/2
100% Functions 7/7
92.85% Lines 13/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 552x         2x 18x               13x                 9x   9x 4x     5x 5x                     5x               5x 8x 8x      
import { CACHE_KEY_PREFIX, Cacheable, getKeyWithPrefix, ICache, removePrefixFromKey } from './shared'
 
/**
 * Implementation of caching that uses session storage
 * */
export class SessionStorageCache implements ICache {
  constructor(public prefix: string = CACHE_KEY_PREFIX) {}
 
  /**
   * It takes a key and an entry, and sets the entry in the session storage with the key
   * @param {string} key - The key to store the entry under.
   * @param {Cacheable} entry - The value to be stored in the cache.
   */
  public set<T = Cacheable>(key: string, entry: T) {
    window.sessionStorage.setItem(getKeyWithPrefix(key, this.prefix), JSON.stringify(entry))
  }
 
  /**
   * It gets the value of the key from the session storage, parses it as JSON, and returns it
   * @param {string} key - The key to store the data under.
   * @returns The value of the key in the sessionStorage.
   */
  public get<T = Cacheable>(key: string) {
    const json = window.sessionStorage.getItem(getKeyWithPrefix(key, this.prefix))
 
    if (!json) {
      return
    }
 
    try {
      return JSON.parse(json) as T
    } catch (e) {
      return
    }
  }
 
  /**
   * It removes the item from session storage with the given key
   * @param {string} key - The key to store the value under.
   */
  public remove(key: string) {
    window.sessionStorage.removeItem(getKeyWithPrefix(key, this.prefix))
  }
 
  /**
   * It returns an array of all the keys in the session storage that start with the prefix
   * @returns An array of all the keys in the sessionStorage that start with the prefix.
   */
  public allKeys() {
    return Object.keys(window.sessionStorage)
      .filter((key) => key.startsWith(this.prefix))
      .map((key) => removePrefixFromKey(key, this.prefix))
  }
}