zanata/etagCacheCollection.js

'use strict';

/**
 * The ETag Cache Collection Management
 * @exports zanata/etagCacheCollection
 *
 * @requires zanata/etagCache
 */
const ETagCache = require('./etagCache.js');

/**
 * @class
 * @classdesc The ETagCache collection class
 */
class ETagCacheCollection {

  /**
   *
   *
   * @param {object} obj - the JSON object represented by `JSON.stringify()` this class.
   *
   * @throws {TypeError}
   */
  constructor(obj) {
    if (!(this instanceof ETagCacheCollection)) {
      throw new TypeError('Unable to call a class as a function');
    }
    let self = this;
    this.cache = {};
    if (obj != undefined) {
      Object.keys(obj).forEach(function(k) {
        if (k !== 'version')
          self.add(new ETagCache(obj[k]));
      });
    }
  }

  buildKey(cache) {
    return cache.getDocId() + '-' + cache.getVersionId() + '-' + cache.getLanguage();
  }

  /**
   * Add a cache into the collection
   *
   * @param {module:zanata/etagCache~ETagCache} cache - ETagCache
   */
  add(cache) {
    this.cache[this.buildKey(cache)] = cache;
    return this;
  }

  /**
   * Obtain the ETagCache
   *
   * @param {string} docId - the document id
   * @param {string} versionId - the version id
   * @param {string} lang - the language name
   *
   * @returns {module:zanata/etagCache~ETagCache|undefined} `ETagCache` if any. otherwise `undefined`.
   */
  get(docId, versionId, lang) {
    let v = new ETagCache()
        .setDocId(docId)
        .setVersionId(versionId)
        .setLanguage(lang);
    return this.cache[this.buildKey(v)];
  }

  /**
   * The callback function to iterate caches.
   *
   * @callback forEachCallback
   * @param {module:zanata/etagCache~ETagCache} ETagCache
   */

  /**
   * Iterate caches
   *
   * @param {module:zanata/etagCacheCollection~forEachCallback} callback - the callback function to iterate caches
   */
  forEach(callback) {
    this.cache.forEach(callback);
  }

  /**
   * Convert caches to JSON
   *
   * @returns {object} the JSON object
   */
  toJSON() {
    return JSON.stringify(this.cache);
  }

}

module.exports = ETagCacheCollection;