All files / services/internal localStorageService.ts

88.63% Statements 39/44
75% Branches 9/12
100% Functions 5/5
88.63% Lines 39/44

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 451x 1x 1x 1x 1x 1x 2x 2x 2x 1x 2x 2x 2x       2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 1x 1x 2x 2x 2x 2x 1x 1x 8x 1x 1x 8x 1x 2x 1x 1x  
import { Container, Service } from 'typedi';
import { LocalStorageKey } from '@constants/site';
import { getLog } from './logService';
 
@Service()
export class LocalStorageService {
  get = <T>(key: string): T | null => {
    const dataStr = localStorage.getItem(key);
    if (dataStr == null) return null;
    try {
      const obj = JSON.parse(dataStr || '{}');
      return obj;
    } catch (err) {
      getLog().e('LocalStorageService get', err);
      return null;
    }
  };
 
  set = <T>(key: string, value: T): void => {
    try {
      const valueStr = JSON.stringify(value);
      localStorage.setItem(key, valueStr);
    } catch (err) {
      getLog().e('LocalStorageService set', err);
    }
  };
 
  removeAllTrackedKeys = () => {
    const ownKeys: Array<string> = [];
    for (const localKey in LocalStorageKey) {
      if (Object.prototype.hasOwnProperty.call(LocalStorageKey, localKey)) {
        ownKeys.push((LocalStorageKey as { [prop: string]: string })[localKey]);
      }
    }
 
    for (const key in localStorage) {
      if (ownKeys.includes(key)) {
        localStorage.removeItem(key);
      }
    }
  };
}
 
export const getLocalStorage = () => Container.get(LocalStorageService);