All files / ima/storage SessionStorage.js

37.5% Statements 15/40
0% Branches 0/11
50% Functions 7/14
37.5% Lines 15/40
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211          4x                               4x             4x             4x             8x             5x 5x                           12x 12x                                         12x             2x 2x             9x 9x                                                                                                                                                                                                                     4x  
import ns from '../namespace';
import GenericError from '../error/GenericError';
import Storage from './Storage';
import Window from '../window/Window';
 
ns.namespace('ima.storage');
 
/**
 * Implementation of the {@codelink Storage} interface that relies on the
 * native {@code sessionStorage} DOM storage for storing its entries.
 */
export default class SessionStorage extends Storage {
  static get $dependencies() {
    return [Window];
  }
 
  /**
	 * Initializes the session storage.
	 * @param {Window} window
	 */
  constructor(window) {
    super();
 
    /**
		 * The DOM storage providing the actual storage of the entries.
		 *
		 * @type {Storage}
		 */
    this._storage = window.getWindow().sessionStorage;
  }
 
  /**
	 * @inheritdoc
	 */
  init() {
    return this;
  }
 
  /**
	 * @inheritdoc
	 */
  has(key) {
    return !!this._storage.getItem(key);
  }
 
  /**
	 * @inheritdoc
	 */
  get(key) {
    try {
      return JSON.parse(this._storage.getItem(key)).value;
    } catch (error) {
      throw new GenericError(
        'ima.storage.SessionStorage.get: Failed to parse a session ' +
          `storage item value identified by the key ${key}: ` +
          error.message
      );
    }
  }
 
  /**
	 * @inheritdoc
	 */
  set(key, value) {
    try {
      this._storage.setItem(
        key,
        JSON.stringify({
          created: Date.now(),
          value
        })
      );
    } catch (error) {
      let storage = this._storage;
      let isItemTooBig =
        storage.length === 0 ||
        (storage.length === 1 && storage.key(0) === key);
 
      if (isItemTooBig) {
        throw error;
      }
 
      this._deleteOldestEntry();
      this.set(key, value);
    }
 
    return this;
  }
 
  /**
	 * @inheritdoc
	 */
  delete(key) {
    this._storage.removeItem(key);
    return this;
  }
 
  /**
	 * @inheritdoc
	 */
  clear() {
    this._storage.clear();
    return this;
  }
 
  /**
	 * @inheritdoc
	 */
  keys() {
    return new StorageIterator(this._storage);
  }
 
  /**
	 * @override
	 */
  size() {
    return this._storage.length;
  }
 
  /**
	 * Deletes the oldest entry in this storage.
	 */
  _deleteOldestEntry() {
    let oldestEntry = {
      key: null,
      created: Date.now() + 1
    };
 
    for (let key of this.keys()) {
      let value = JSON.parse(this._storage.getItem(key));
      if (value.created < oldestEntry.created) {
        oldestEntry = {
          key,
          created: value.created
        };
      }
    }
 
    if (typeof oldestEntry.key === 'string') {
      this.delete(oldestEntry.key);
    }
  }
}
 
/**
 * Implementation of the iterator protocol and the iterable protocol for DOM
 * storage keys.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
 */
class StorageIterator {
  /**
	 * Initializes the DOM storage iterator.
	 *
	 * @param {Storage} storage The DOM storage to iterate through.
	 */
  constructor(storage) {
    /**
		 * The DOM storage being iterated.
		 *
		 * @type {Storage}
		 */
    this._storage = storage;
 
    /**
		 * The current index of the DOM storage key this iterator will return
		 * next.
		 *
		 * @type {number}
		 */
    this._currentKeyIndex = 0;
  }
 
  /**
	 * Iterates to the next item. This method implements the iterator protocol.
	 *
	 * @return {{done: boolean, value: (undefined|string)}} The next value in
	 *         the sequence and whether the iterator is done iterating through
	 *         the values.
	 */
  next() {
    if (this._currentKeyIndex >= this._storage.length) {
      return {
        done: true,
        value: undefined
      };
    }
 
    let key = this._storage.key(this._currentKeyIndex);
    this._currentKeyIndex++;
 
    return {
      done: false,
      value: key
    };
  }
 
  /**
	 * Returns the iterator for this object (this iterator). This method
	 * implements the iterable protocol and provides compatibility with the
	 * {@code for..of} loops.
	 *
	 * @return {StorageIterator} This iterator.
	 */
  [Symbol.iterator]() {
    return this;
  }
}
 
ns.ima.storage.SessionStorage = SessionStorage;