All files index.ts

90.47% Statements 19/21
91.66% Branches 11/12
100% Functions 10/10
90.47% Lines 19/21

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 55 56 57 58 59 60 61 62 63 64 65          35x     37x 37x       1x 1x     35x 35x   35x 35x                   19x       17x         17x       9x       4x 4x   2x 2x         3x       5x      
type SynthexStorageValue = string;
 
type SynthexStorageData = Record<string, SynthexStorageValue>;
 
function isStorageData(value: unknown): value is SynthexStorageData {
  return (
    typeof value === "object" &&
    value !== null &&
    Object.keys(value).every((key) => typeof key === "string") &&
    Object.values(value).every((value) => typeof value === "string")
  );
}
 
export class SynthexStorage {
  public static mainKey = "synthex-storage";
 
  private static getCurrentData(): SynthexStorageData {
    try {
      const value: unknown = JSON.parse(localStorage.getItem(this.mainKey) || "{}");
 
      Eif (isStorageData(value)) {
        return value;
      }
    } catch {
      return {};
    }
 
    return {};
  }
 
  private static setCurrentData(data: SynthexStorageData): void {
    localStorage.setItem(this.mainKey, JSON.stringify(data));
  }
 
  public static set(key: string, value: SynthexStorageValue): void {
    const data = {
      ...this.getCurrentData(),
      [key]: value,
    };
 
    this.setCurrentData(data);
  }
 
  public static get(key: string): SynthexStorageValue | null {
    return this.getCurrentData()[key] ?? null;
  }
 
  public static remove(key: string): void {
    const data = { ...this.getCurrentData() };
    if (key in data) {
      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete -- the key is valid
      delete data[key];
      this.setCurrentData(data);
    }
  }
 
  public static clear(): void {
    localStorage.removeItem(this.mainKey);
  }
 
  public static getAll(): SynthexStorageData {
    return this.getCurrentData();
  }
}