All files / src/properties StorageManager.ts

100% Statements 18/18
83.33% Branches 5/6
100% Functions 6/6
100% Lines 18/18

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            1x 1x           1x               16x 16x 1x             1x 27x 27x               1x 12x             1x 24x           1x 1x 1x 1x   1x  
/*
* StorageManager.ts
* @author Abhilash Panwar (abpanwar) Hector Hernandez (hectorh)
* @copyright Microsoft 2020
* File containing apis to help store properties in storage.
*/
import { getGlobal, Utils } from '@microsoft/1ds-core-js';
import { _EISessionKey, _EIPreviousKey, _MSEI } from './Constants';
 
/**
 * This class adds ability to store properties in various types of storages or custom storage.
 * TODO(abpanwar): This class will change once we add support for other storage types, custom storage and error handling.
 */
export default class StorageManager {
  private _storage: Storage;
 
  /**
   * Creates an instance of the storage manager class to determine the storage that needs to be used.
   * @param storageDisabled Whether storage is disabled due to user not providing consent.
   */
  constructor(storageDisabled: boolean) {
    this._storage = StorageManager._getLocalStorage();
    if (storageDisabled && this._storage) {
      this._deleteAllStorage();
    }
  }  
 
  /**
   * Get local storage if available.
   */
  static _getLocalStorage(): Storage {
    const global = getGlobal() || <Window>{};
    return <Storage>(global['localStorage']);
  }
 
  /**
   * Stores a key value pair in the chosen storage.
   * @param key key to be stored
   * @param value value to be stored
   */
  _setProperty(key: string, value: string) {
    this._storage.setItem(key, value);
  }
 
  /**
   * Returns a value associated with the passed key. Null if key is not present.
   * @param key key to be used to return the value
   */
  _getProperty(key: string): string {
    return this._storage.getItem(key);
  }
 
  /**
   * Deletes all data stored in cookies or local storage.
   */
  private _deleteAllStorage() {
    this._storage.removeItem(_EISessionKey);
    this._storage.removeItem(_EIPreviousKey);
    Utils.deleteCookie(_MSEI);
  }
}