All files / src/cache cache-local-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 372x         2x 14x     15x       19x   19x 9x     10x 10x             5x       5x 8x 8x      
import { ICache, Cacheable, CACHE_KEY_PREFIX, getKeyWithPrefix, removePrefixFromKey } from './shared'
 
/**
 * Implementation of caching that uses local storage
 * */
export class LocalStorageCache implements ICache {
  constructor(public prefix: string = CACHE_KEY_PREFIX) {}
 
  public set<T = Cacheable>(key: string, entry: T) {
    window.localStorage.setItem(getKeyWithPrefix(key, this.prefix), JSON.stringify(entry))
  }
 
  public get<T = Cacheable>(key: string) {
    const json = window.localStorage.getItem(getKeyWithPrefix(key, this.prefix))
 
    if (!json) {
      return
    }
 
    try {
      return JSON.parse(json) as T
    } catch (e) {
      return
    }
  }
 
  public remove(key: string) {
    window.localStorage.removeItem(getKeyWithPrefix(key, this.prefix))
  }
 
  public allKeys() {
    return Object.keys(window.localStorage)
      .filter((key) => key.startsWith(this.prefix))
      .map((key) => removePrefixFromKey(key, this.prefix))
  }
}