All files / ima/cache CacheImpl.js

91.38% Statements 53/58
90.24% Branches 37/41
91.67% Functions 11/12
91.38% Lines 53/58
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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258      3x                                                           18x             18x         18x             18x             18x             18x             3x             13x 4x     9x 9x 6x     3x   3x             6x 5x   5x     1x             54x       54x         54x             3x             1x 1x                           2x   2x 3x   3x 3x 1x                       2x     1x             3x 32x 32x                       25x           5x   5x     20x       20x 1x 4x               20x 6x 13x 1x             1x         19x                       59x         5x     54x       3x  
import ns from '../namespace';
import Cache from './Cache';
 
ns.namespace('ima.cache');
 
/**
 * Configurable generic implementation of the {@codelink Cache} interface.
 *
 * @example
 *   if (cache.has('model.articles')) {
 *     return cache.get('model.articles');
 *   } else {
 *     let articles = getArticlesFromStorage();
 *     // cache for an hour
 *     cache.set('model.articles', articles, 60 * 60 * 1000);
 *   }
 */
export default class CacheImpl extends Cache {
  /**
	 * Initializes the cache.
	 *
	 * @param {Storage} cacheStorage The cache entry storage to use.
	 * @param {CacheFactory} factory Which create new instance of cache entry.
	 * @param {vendor.$Helper} Helper The IMA.js helper methods.
	 * @param {{ttl: number, enabled: boolean}} [config={ttl: 30000, enabled: false}]
	 *        The cache configuration.
	 */
  constructor(
    cacheStorage,
    factory,
    Helper,
    config = { ttl: 30000, enabled: false }
  ) {
    super();
 
    /**
		 * Cache entry storage.
		 *
		 * @type {Storage}
		 */
    this._cache = cacheStorage;
 
    /**
		 * @type {CacheFactory}
		 */
    this._factory = factory;
 
    /**
		 * Tha IMA.js helper methods.
		 *
		 * @type {vendor.$Helper}
		 */
    this._Helper = Helper;
 
    /**
		 * Default cache entry time to live in milliseconds.
		 *
		 * @type {number}
		 */
    this._ttl = config.ttl;
 
    /**
		 * Flag signalling whether the cache is currently enabled.
		 *
		 * @type {boolean}
		 */
    this._enabled = config.enabled;
  }
 
  /**
	 * @inheritdoc
	 */
  clear() {
    this._cache.clear();
  }
 
  /**
	 * @inheritdoc
	 */
  has(key) {
    if (!this._enabled || !this._cache.has(key)) {
      return false;
    }
 
    let cacheEntry = this._cache.get(key);
    if (cacheEntry && !cacheEntry.isExpired()) {
      return true;
    }
 
    this.delete(key);
 
    return false;
  }
 
  /**
	 * @inheritdoc
	 */
  get(key) {
    if (this.has(key)) {
      let value = this._cache.get(key).getValue();
 
      return this._clone(value);
    }
 
    return null;
  }
 
  /**
	 * @inheritdoc
	 */
  set(key, value, ttl = null) {
    Iif (!this._enabled) {
      return;
    }
 
    let cacheEntry = this._factory.createCacheEntry(
      this._clone(value),
      ttl || this._ttl
    );
 
    this._cache.set(key, cacheEntry);
  }
 
  /**
	 * @inheritdoc
	 */
  delete(key) {
    this._cache.delete(key);
  }
 
  /**
	 * @inheritdoc
	 */
  disable() {
    this._enabled = false;
    this.clear();
  }
 
  /**
	 * @inheritdoc
	 */
  enable() {
    this._enabled = true;
  }
 
  /**
	 * @inheritdoc
	 */
  serialize() {
    let dataToSerialize = {};
 
    for (let key of this._cache.keys()) {
      let serializeEntry = this._cache.get(key).serialize();
 
      Eif ($Debug) {
        if (!this._canSerializeValue(serializeEntry.value)) {
          throw new Error(
            `ima.cache.CacheImpl:serialize An ` +
              `attempt to serialize ` +
              `${serializeEntry.value.toString()}, stored ` +
              `using the key ${key}, was made, but the value ` +
              `cannot be serialized. Remove this entry from ` +
              `the cache or change its type so that can be ` +
              `serialized using JSON.stringify().`
          );
        }
      }
 
      dataToSerialize[key] = serializeEntry;
    }
 
    return JSON.stringify(dataToSerialize).replace(/<\/script/g, '<\\/script');
  }
 
  /**
	 * @inheritdoc
	 */
  deserialize(serializedData) {
    for (let key of Object.keys(serializedData)) {
      let cacheEntryItem = serializedData[key];
      this.set(key, cacheEntryItem.value, cacheEntryItem.ttl);
    }
  }
 
  /**
	 * Tests whether the provided value can be serialized into JSON.
	 *
	 * @param {*} value The value to test whether or not it can be serialized.
	 * @return {boolean} {@code true} if the provided value can be serialized
	 *         into JSON, {@code false} otherwise.
	 */
  _canSerializeValue(value) {
    if (
      value instanceof Date ||
      value instanceof RegExp ||
      value instanceof Promise ||
      typeof value === 'function'
    ) {
      console.warn('The provided value is not serializable: ', value);
 
      return false;
    }
 
    Iif (!value) {
      return true;
    }
 
    if (value.constructor === Array) {
      for (let element of value) {
        Iif (!this._canSerializeValue(element)) {
          console.warn('The provided array is not serializable: ', value);
 
          return false;
        }
      }
    }
 
    if (typeof value === 'object') {
      for (let propertyName of Object.keys(value)) {
        if (!this._canSerializeValue(value[propertyName])) {
          console.warn(
            'The provided object is not serializable due to the ' +
              'following property: ',
            propertyName,
            value
          );
 
          return false;
        }
      }
    }
 
    return true;
  }
 
  /**
	 * Attempts to clone the provided value, if possible. Values that cannot be
	 * cloned (e.g. promises) will be simply returned.
	 *
	 * @param {*} value The value to clone.
	 * @return {*} The created clone, or the provided value if the value cannot
	 *         be cloned.
	 */
  _clone(value) {
    if (
      value !== null &&
      typeof value === 'object' &&
      !(value instanceof Promise)
    ) {
      return this._Helper.clone(value);
    }
 
    return value;
  }
}
 
ns.ima.cache.CacheImpl = CacheImpl;