All files / lib/utils StorageController.ts

100% Statements 34/34
90% Branches 9/10
100% Functions 10/10
100% Lines 28/28

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   2x 30x   30x   30x 30x   67x   67x       67x     2x 26x     2x 18x 15x     4x   3x     2x 4x     2x 3x     2x 16x 13x     16x 16x     32x   2x  
import deepmerge from 'deepmerge';
import compareVersions from 'compare-versions';
 
export class StorageController {
  separator = '/';
 
  componentTree: Record<string, string[]> = {};
 
  constructor(private prefix: string, private storage: Storage) {
    this.componentTree = Object.keys(this.storage)
      .map(key => {
        const [, comp, componentVersion] = key.split(this.separator);
 
        return {
          [comp]: [componentVersion]
        };
      })
      .reduce((tree, key) => deepmerge(tree, key), {});
  }
 
  getStorageKey(name: string, componentVersion: string): string {
    return [this.prefix, name, componentVersion].join(this.separator);
  }
 
  getLatestVersion(name: string): string | undefined {
    if (!this.componentTree[name]) {
      return;
    }
 
    const [latestComponentVersion] = this.componentTree[name].sort((x: string, y: string) => compareVersions(y, x));
 
    return latestComponentVersion;
  }
 
  has(name: string, componentVersion: string): boolean {
    return !!(this.componentTree[name] && this.componentTree[name].includes(componentVersion));
  }
 
  async getItem(name: string, componentVersion: string): Promise<string | null> {
    return await this.storage.getItem(this.getStorageKey(name, componentVersion));
  }
 
  async setItem(name: string, componentVersion: string, code: string): Promise<void> {
    if (!this.componentTree[name]) {
      this.componentTree[name] = [];
    }
 
    Eif (!this.componentTree[name].includes(componentVersion)) {
      this.componentTree[name].push(componentVersion);
    }
 
    await this.storage.setItem(this.getStorageKey(name, componentVersion), code);
  }
}