All files StorageController.ts

100% Statements 30/30
100% Branches 2/2
100% Functions 8/8
100% Lines 24/24

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 551x 1x   1x 9x   9x   9x 9x   21x           21x     1x 9x     1x   1x     2x   1x     1x 2x     1x 1x     1x   1x       1x     2x   1x  
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] = [];
    }
 
    if (!this.componentTree[name].includes(componentVersion)) {
      this.componentTree[name].push(componentVersion);
    }
 
    await this.storage.setItem(this.getStorageKey(name, componentVersion), code);
  }
}