All files / modules/acute-common/src/services local-storage.service.ts

13.04% Statements 3/23
0% Branches 0/12
0% Functions 0/5
9.09% Lines 2/22

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                            1x 1x                                                                      
import { Injectable } from '@angular/core';
import { Logger } from '@bitblit/ratchet-common/logger/logger';
 
 
export function storageFinder(): Storage | null {
  if (typeof window !== 'undefined') {
    if (typeof window.localStorage !=='undefined') {
      return window.localStorage;
    }
  }
  return null;
}
 
@Injectable({providedIn: 'root'})
export class LocalStorageService<T> {
  private static readonly APP_NAME: string = 'Scribe';
 
  public get storageReady(): boolean {
    return !!storageFinder();
  }
 
  public clear(): void {
    this.update({ } as T );
  }
 
  public update(value: T): T {
    if (this.storageReady) {
      const toSave: T = value || ({} as T);
      const saveString: string = JSON.stringify(toSave);
      Logger.info('Updating storage to %s', saveString);
      localStorage.setItem(LocalStorageService.APP_NAME, saveString);
      return toSave;
    } else {
      Logger.info('Skipping update - storage not ready : %j', value);
      return {} as T;
    }
  }
 
  fetch(): T {
    if (this.storageReady) {
      const loadString: string = localStorage.getItem(LocalStorageService.APP_NAME) || '{}';
      const rval: T = JSON.parse(loadString) as T;
      return rval;
    } else {
      Logger.info('Skipping fetch - storage not ready');
      return {} as T;
    }
  }
 
}